I'm trying to use this provider class to save new user data to database, but I always get this error
"FatalErrorException: Error: Call to a member function get() on a non-object"
The problem is get('security.encoder_factory')
is somehow not working. I'm using this to encode the password. Is there any other way or any fix for this code so i can encode the password without getting an error?
this is my provider class code:
namespace xxxx\yyyyBundle\Provider;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUserProvider;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;'
class Provider extends OAuthUserProvider
{
//.....
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
//.....
if ( !count($result) ) {
$user = new User();
$user->setUsername(xxxxx);
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
$user->setPassword($encoder->encodePassword(xxxxx, $user->getSalt()));
$user->setStatus(xxxxx);
$user->setFID($facebook_id);
$em = $this->doctrine->getManager();
$em->persist($user);
$id = $em->flush();
} else {
$id = $result[0]['id'];
}
//set id
$this->session->set('id', $id);
//parent:: returned value
return $this->loadUserByUsername($response->getNickname());
}
}
this exact doctrine code working on the user registration with form.
It looks like you are using HWIOAuthBundle
. I don't know this bundle but a cursory glace at its source suggests it's not container aware... Hence your issue: you are trying to call a method on a non-object.
Since you are extending OAuthUserProvider
, you could set up your Provider
class as a service itself, inject the container (or better yet just the security.encoder_factory
).
This is not tested but something like:
<?php
namespace Foo\BarBundle\Provider;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUserProvider;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
class BazProvider extends OAuthUserProvider
{
private $encoder;
public function __construct(EncoderFactoryInterface $encoder)
{
// assign injected object as property
$this->encoder = $encoder;
}
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$user = new User();
// use injected object
$encoder = $this->encoder->getEncoder($user);
// implement
}
}
In your bundle's services.yml
services:
baz_provider:
class: Foo\BarBundle\Provider\BazProvider
arguments:
- @security.encoder_factory
Like any service, you call this in any container aware context (such as a controller) like so:
$bazProvider = $this->get('baz_provider');
Hope this helps :)
EDIT
More reading here: http://symfony.com/doc/current/components/dependency_injection/types.html#constructor-injection