在null symfony2上调用成员函数has()

时间:2016-08-03 20:08:21

标签: php symfony service

我有5类Categoria,Produto,Subcategoria,Subproduto和Comanda,并且在所有类中执行搜索我尝试提供如下服务:

namespace AppBundle\Controller;


use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AccessClassController extends Controller{

    /**
     * Retorna todas as categorias ativas
     */
    public function CategoriasAtivasAction()
    {
        $em = $this->getDoctrine()->getManager();

        $categorias = $em->getRepository('AppBundle:Categoria')->findByAtivo(1);

        return $categorias;
    }
}
 

我尝试在ComandaController上访问该服务

class ComandaController extends Controller
{
...
public function newAction(Request $request, $id)
    {
        $comanda = new Comanda();

        $categorias = $this->get('categorias.ativas')->CategoriasAtivasAction();
...

然后symfony返回错误

Call to a member function has() on null 500 Internal Server Error - FatalThrowableError

我的services.yml有


services:
  categorias.ativas:
     class: AppBundle\Controller\AccessClassController

怎么了?

1 个答案:

答案 0 :(得分:2)

根据Symfony文档,Symfony未正式推荐将控制器定义为服务。即使你需要使用,你也可以做到这一点。根据您的代码,您尚未在服务中传递服务容器对象。请进行以下更改并尝试。

在services.yml文件中

services:
   categorias.ativas:
      class: AppBundle\Controller\AccessClassController
      arguments: ["@service_container"]

在AccessClassController文件中

namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class AccessClassController extends Controller{

  /**
  * Retorna todas as categorias ativas
  */
  public function CategoriasAtivasAction()
  {
    $em = $this->container->get('doctrine')->getManager();

    $categorias = $em->getRepository('AppBundle:Categoria')->findByAtivo(1);

    return $categorias;
  }
}