简体   繁体   中英

Call to a member function has() on null symfony2

I have 5 class Categoria, Produto, Subcategoria, Subproduto and Comanda and for execute search in all classes i try make a service like:

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

And i try access the service on ComandaController

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

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

Then symfony return error

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

My services.yml has

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

Whats wrong?

As per Symfony documentation, Defining controllers as services is not officially recommended by Symfony. Even though if you need to use you can do that. As per your code you haven't passed service container object in service. Please do the following changes and try.

In your services.yml file

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

And in your AccessClassController file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM