【发布时间】:2017-06-09 13:49:31
【问题描述】:
自从过去 4 小时以来,我一直在尝试了解 Symfony 2 服务的逻辑以及它们如何集成到应用程序中......
基本上我正在尝试通过服务设置我的 EntityManager 并在控制器中使用它
我有以下结构
Bundle1/Controller/Bundle1Controller.php
Bundle1/Services/EntityService.php
Bundle2/Controller/Bundle2Controller.php
Bundle3/Controller/Bundle3Controller.php
....
我正在尝试创建一个具有不同入口点的 REST API,这就是我使用多个捆绑包的原因bundle2,bundle3....
逻辑如下:
- 一个 POST 被触发到 Bundle2/Controller/Bundle2Controller.php
- Bundle2Controller.php 实例化一个 new() Bundle1Controller.php
- 在 Bundle1Controller 内部,我想访问服务
entity_service以获取我的 EntityManager
我有 2 个案例我设法登陆...
- 在
Bundle1/Controller/Bundle1Controller中,如果我尝试$this->container或$this->get('entity_service'),我每次都会得到null - 如果我在
Bundle2/Controller/Bundle2Controller中设置容器并尝试$this->get('entity_service')我得到You have requested a non-existent service "entity_service"
我会把所有代码放在下面
Bundle1/Controller/Bundle1Controller
<?php
namespace Bundle1\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use EntityBundle\Entity\TestEntity;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
class Bundle1Controller extends Controller
{
/**
* @param $response
* @return array
*/
public function verifyWebHookRespone($response){
$em = $this->get('entity_service')->getEm();
$array = json_decode($response);
$mapping = $em->getRepository('EntityBundle:TestEntity')
->findBy(["phone" => $array['usernumber']]);
return $mapping;
}
}
Bundle2/Controller/Bundle2Controller.php
<?php
namespace Bundle2\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Bundle1\Controller\Bundle1Controller;
class Bundle2Controller extends Controller
{
public function webhookAction(Request $request)
{
$data = $request->request->get('messages');
$model = new Bundle1Controller();
$responseMessage = $model->verifyWebHookRespone($data);
return new Response($responseMessage, Response::HTTP_CREATED, ['X-My-Header' => 'My Value']);
}
}
Bundle1/Services/EntityService.php
<?php
namespace EntityBundle\Services;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\Container;
class EntityService
{
protected $em;
private $container;
public function __construct(EntityManager $entityManager, Container $container)
{
$this->em = $entityManager;
$this->container = $container;
}
/**
* @return EntityManager
*/
public function getEm()
{
return $this->em;
}
}
services.yml
services:
entity_service:
class: Bundle1\Services\EntityService
arguments: [ "@doctrine.orm.entity_manager" , "@service_container" ]
谁能帮我解决这个问题? 无论是捆绑包还是其他服务,我如何注册服务并从任何地方调用它?
【问题讨论】:
标签: php symfony-2.8