Paul
Paul

Reputation: 1390

Call an helper from a service

I would like to call an helper from my service.

$notificationService = $this->get('Notification');

Attempted to call an undefined method named "get" of class

Upvotes: 1

Views: 2232

Answers (1)

Wouter J
Wouter J

Reputation: 41934

Symfony isn't magic. Symfony is just PHP. That's the most important thing to remember when working with Symfony.

So if there is no get() method in your class, you can't call the method. In your controller, you extend from a base Controller of the FrameworkBundle. This class does contain such a method, so in a controller you can call this method.

Now, you still want to use the Notification service in your new service. Instead of getting it from the container, let the container inject it in your service when it's creating it. You do this with some service config:

# app/config/services.yml
services:
    app.your_service:
        class: AppBundle\Some\Class
        arguments: ['@Notification'] # <<-- this tells to inject the service

And then adapting this in your class:

class SomeClass
{
    private $nofication;

    public function __construct(NotificationInterface $notification)
    {
        $this->notification = $notification;
    }
}

There is a lot more to explain about this. See http://symfony.com/doc/current/book/service_container

Upvotes: 3

Related Questions