注册服务并在此之后致电

时间:2017-04-18 13:06:22

标签: php symfony symfony-2.3 php-5.5

我的服务有问题。 所以我的服务是:

services:
    app.one_level_game:
        class: App\DesktopBundle\Lib\Game\OneLevel
        arguments: [ "@doctrine.orm.entity_manager", %game_name%, %user_id% ]

我的班级OneLevel:

namespace App\DesktopBundle\Lib\Game;

use App\DesktopBundle\Entity\OnelevelHistory;
use App\DesktopBundle\Lib\DoctrineService;
use Symfony\Component\Yaml\Yaml;
use Doctrine\ORM\EntityManager;


class OneLevel{

protected $em;
/**
 * Constructor of application
 * @param $game_name
 * @param $user_id
 * @param $em
 */
public function __construct(EntityManager $em, $game_name, $user_id){
    $this->a_config     = Yaml::parse(file_get_contents(__DIR__.'/../../Resources/config/game.yml'));
    $this->game_name    = $game_name;
    $this->user_id      = $user_id;
    $this->score        = 0;
    $this->em           = $em;
}

之后我试着打电话:

$o_oneLevel = $this->get('app.one_level_game', $game_name, $user_id);

错误是:The service "app.one_level_game" has a dependency on a non-existent parameter "game_name". 你能帮帮我吗,我做错了什么? Thx提前和抱歉我的英语。

1 个答案:

答案 0 :(得分:2)

如果您有%game_name%

services:
    app.one_level_game:
        class: App\DesktopBundle\Lib\Game\OneLevel
        arguments: [ "@doctrine.orm.entity_manager", %game_name%, %user_id% ]

game_name(和parameters.yml

中应该有parameters.yml.dist
#paremeters.yml
    game_name: MyGameName

但是如果你想在调用时传递参数,你可以通过方法调用(解决方案1)传递paremetrs或通过setter(解决方案2)设置它[/ p>

解决方案#1

$service = $this->get('app.one_level_game');
$service->doSomething($gameName, $userId);

这是最简单的,但如果您多次致电您的服务,您应该通过它们将它们传递给您的服务。在这种情况下,解决方案#2更好

解决方案#2

$service = $this->get('app.one_level_game');
$service->setGameName($gameName);
$service->setUserId($userId);

$service->doSomething();

并在OneLevel类中

class OneLevel{

   protected $em;

   public function __construct(EntityManager $em){
       $this->a_config     = Yaml::parse(file_get_contents(__DIR__.'/../../Resources/config/game.yml'));
       $this->score        = 0;
       $this->em           = $em;
   }

   public function setGameName($gameName)
   {
        $this->gameName = $gameName;
   }

   public function setUserId($userId)
   {
        $this->userId = $userId;
   }

如果这两个解决方案不够,您应该检查您的代码架构