0

I have a service like this :

  services:
    prodacom_authentication.encode:
      class: Prodacom\AuthenticationBundle\Service\Encode
      arguments: ["@security.context"]

the service function i want to call in a controller:

public function encodePassword() {
    $factory = $this->get('security.encoder_factory');
    $user = new Prodacom\MainBundle\Entity\PdbUser();

    $encoder = $factory->getEncoder($user);
    $password = $encoder->encodePassword('ryanpass', $user->getSalt());
    var_dump($password);
    $user->setPassword($password);
}

i want to call the function encodePassword in the authenticationController.php.

    $this->get('prodacom_authentication.encode')->encodePassword();

but i keep getting this error :

    Attempted to call method "get" on class "Prodacom\AuthenticationBundle\Service\Encode" in C:\htdocs\domeinbeheer\src\Prodacom\AuthenticationBundle\Service\Encode.php line 12.

any ideas ???

1
  • 1
    If You want to use ->get('') in Your service You have to pass container service to It. Commented Sep 15, 2014 at 10:17

2 Answers 2

1

The problem is in the second line in your method, where you call: $this->get('security.encoder_factory')

Within your service, the method get() is not defined if you have not implemented it yourself. Your controller has it, because it extends a class called ContainerAware, that implements this method.

You can now either inject the complete dependency-container (not recommended) or just inject the services you need into your service. Here's a list of different ways you can use to inject services into your service: http://symfony.com/doc/current/components/dependency_injection/types.html

I saw you're already familiar with constructor-injection ...

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to use a service in another one, you have to use dependency injection.

$this->get() is available in a controller context only.

You'll find a full example in official documentation : http://symfony.com/doc/2.3/components/dependency_injection/introduction.html

Note : You have to pass each service or parameters you need in injection. Inject the container to call others services can seems more easy, but is a bad practice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.