B
B
blitzkrieg3932018-03-11 19:40:45
symfony
blitzkrieg393, 2018-03-11 19:40:45

How to properly create a service in Symfony 3.4?

Good day! Please tell me how to create a service in symfony 3.4 correctly. Everything seems to be done according to the manuals, but it still crashes Uncaught PHP ExceptionSymfony\Component\DependencyInjection\Exception\ServiceNotFoundException: "You have requested a non-existent service "obb.naming"
Controller:

namespace Ost\BlogBundle\Controller;

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;

    class TestController extends Controller
    {
        public function heyAction()
        {
            $name= 'qqqq';
            $naming = $this->get("obb.naming");
            $naming->setName($name);
            return $this->render("Test/hey.html.twig",array('message'=>$naming->getName()));
        }
    }

The class that I want to make a service:
namespace Ost\BlogBundle\Services;

class Naming
{
    private $name;

    public function setName($name)
    {
        $this->name = $name;
    }
    public function getName()
    {
        return $this->name;
    }
}

Services.yml file (src/Ost/BlogBundle/Resources/config/):
obb.naming:
      class: Ost\BlogBundle\Services\Naming

config.yml file (app/config/):
imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }
    - { resource: "@OstBlogBundle/Resources/config/services.yml" }

I tried it with arguments, I tried passing it to the constructor (with a link to another service), and I tried calling it in the constructor through the container ($this->container->get("obb.naming")) ... maybe I didn't see something. Help, pliz

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bears, 2018-03-11
@bears

In version 3.4, it is customary to name services by the class name, and if the service does not have any specific dependencies, then it does not need to be registered in the services.yml file. In an action, it is better not to use $this->get('...'), but to explicitly pass the required service:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ost\BlogBundle\Services\Naming;
class TestController extends Controller
{
    public function key(Naming $naming)
    {
        
    }
}

This is enough for everything to work as it should.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question