Call to a member function has() on null 500 with S

2019-07-25 18:07发布

问题:

I am having some trouble setting up doctrine to run from the following service file.

<?php

// src/AppBundle/Services/SuperusersService.php
namespace AppBundle\Services;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManager;

class SuperusersService extends Controller
{

    public function sayHello()
    {

        $em = $this->getDoctrine()->getManager();

         // Query here

    }

}

When I run the above I get the following error message.

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

I call the file from the following controller file.

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class LoginController extends Controller
{
    /**
     * @Route("/login")
     */
    public function indexAction(Request $request)
    {

        if(!empty($_POST)){

            ////
            // If for submitted attempt to log the user in.
            ////

            $superusersService = $this->get('app.superusers.services');

            $superusersService->sayHello();

        }

        $name = "Login";

        return $this->render('login/login.html.php', 
        array());

    }
}

Service file

# Learn more about services, parameters and containers at
# http://symfony.com/doc/current/service_container.html
parameters:
#    parameter_name: value

services:
#    service_name:
#        class: AppBundle\Directory\ClassName
#        arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
    app.superusers.services:
            class: AppBundle\Services\SuperusersService

Now I have taken a look around at other questions but as of yet I am unable to resolve the above. I think it will have something to do with the setup of the files but I'm not sure what.

回答1:

When a controller is declared as a service the container attribute is no longer present hence you can no longer get a service with

$this->get('service_name')

The solution: You need to inject your dependencies the way you would for a regular service, here is an example

On a side note, i'm not sure if this is just testing code but you should probably avoid using $_POST globals, you can make use of the $request method provided.