【问题标题】:Call to a member function has() on null symfony2在空 symfony2 上调用成员函数 has()
【发布时间】:2016-12-09 17:08:36
【问题描述】:

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

命名空间 AppBundle\控制器; 使用 Symfony\Bundle\FrameworkBundle\Controller\Controller; 类 AccessClassController 扩展控制器{ /** * Retorna todas 作为 categorias ativas */ 公共功能分类AtivasAction() { $em = $this->getDoctrine()->getManager(); $categorias = $em->getRepository('AppBundle:Categoria')->findByAtivo(1); 返回$类别; } }

我尝试访问 ComandaController 上的服务

类 ComandaController 扩展控制器 { ... 公共函数 newAction(请求 $request, $id) { $comanda = 新的 Comanda(); $categorias = $this->get('categorias.ativas')->CategoriasAtivasAction(); ...

然后symfony返回错误

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

我的 services.yml 有

服务: 分类.ativas: 类:AppBundle\Controller\AccessClassController

怎么了?

【问题讨论】:

  • 您不能将控制器(扩展控制器)用作服务。
  • 其实只要注入容器就可以了。这样做没有多大意义。在这种情况下,它是在没有容器的地方创建的 ComandaController。因此有错误。

标签: php symfony service


【解决方案1】:

根据 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;
  }
}

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2014-05-05
    • 2015-07-07
    • 2020-01-13
    相关资源
    最近更新 更多