Я пытаюсь создать регистрационную форму пользователя в Symfony2, но я получаю ошибку spl_object_hash при попытке отправить моего пользователя. Я просто хочу иметь возможность заполнить форму и создать нового пользователя с закодированным паролем в моей базе данных.
Поэтому у меня в основном есть 2 вопроса:
Вот мой код:
User.php
<?php
namespace Acme\FOSUserBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\FOSUserBundle\Entity\User
*
* @ORM\Table(name="users")
* @ORM\Entity(repositoryClass="Acme\FOSUserBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* @ORM\Column(type="string", length=32)
*/
private $salt;
/**
* @ORM\Column(type="string", length=255)
*/
private $password;
/**
* @ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* @ORM\ManyToOne(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
public function __construct()
{
$this->isActive = true;
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/**
* advanced
*/
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
/**
* @inheritDoc
*/
public function getUsername()
{
return $this->username;
}
/**
* @inheritDoc
*/
public function getSalt()
{
return $this->salt;
}
/**
* @inheritDoc
*/
public function getPassword()
{
return $this->password;
}
/**
* @inheritDoc
*/
public function getRoles()
{
return $this->roles;
}
/**
* @param $roles
* @return $this
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* @inheritDoc
*/
public function eraseCredentials()
{
}
/**
* @see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->salt,
));
}
/**
* @see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->salt,
) = unserialize($serialized);
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Set salt
*
* @param string $salt
* @return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Set password
*
* @param string $password
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Set email
*
* @param string $email
* @return User
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isActive
*
* @param boolean $isActive
* @return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* Get isActive
*
* @return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
}
Role.php
<?php
namespace Acme\FOSUserBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="roles")
* @ORM\Entity()
*/
class Role implements RoleInterface
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* @ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* @see RoleInterface
*/
public function getRole()
{
return $this->role;
}
// ... getters and setters for each property
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set role
*
* @param string $role
* @return Role
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Add users
*
* @param \Acme\FOSUserBundle\Entity\User $users
* @return Role
*/
public function addUser(\Acme\FOSUserBundle\Entity\User $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* @param \Acme\FOSUserBundle\Entity\User $users
*/
public function removeUser(\Acme\FOSUserBundle\Entity\User $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
}
RegistrationController.php
<?php
namespace Acme\FOSUserBundle\Controller;
use Acme\FOSUserBundle\Form\Type\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Acme\FOSUserBundle\Entity\User;
class RegistrationController extends Controller
{
public function registerAction()
{
$em = $this->get('doctrine')->getManager();
$request = $this->get('request');
$user = new User();
$form = $this->get('form.factory')->create(new UserType(), $user);
if ('POST' == $request->getMethod()) {
$form->bind($request);
$user->setRoles(array('ROLE_USER'));
$factory = $this->container->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($user->getPassword(), $user->getSalt()); //where $user->password has been bound in plaintext by the form
$user->setPassword($password);
if ($form->isValid()) {
$em->persist($user);
//$em->persist($profile);
$em->flush();
// creates a token and assigns it, effectively logging the user in with the credentials they just registered
$token = new UsernamePasswordToken($user, null, 'main');
$this->get('security.context')->setToken($token);
return $this->redirect($this->generateUrl('Acme_FOSUserBundle_registration_thanks'));
}
}
return $this->render('AcmeFOSUserBundle:Security:register.html.twig', array(
'form' => $form->createView(),
));
}
}
UserType.php
<?php
namespace Acme\FOSUserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('username', null, array('label' => 'Username'));
$builder->add('email', null, array('label' => 'E-mail'));
$builder->add('password', 'repeated', array(
'first_name' => 'password',
'second_name' => 'confirm',
'type' => 'password',
));
$builder->add('Register', 'submit');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\FOSUserBundle\Entity\User'
));
}
public function getName()
{
return 'user';
}
}
?>
security.yml
security:
encoders:
Acme\FOSUserBundle\Entity\User:
algorithm: sha512
encode_as_base64: true
iterations: 10
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
providers:
main:
entity:
class: Acme\FOSUserBundle\Entity\User
property: username
firewalls:
secured_area:
pattern: ^/
anonymous: ~
form_login:
login_path: login
check_path: login_check
logout:
path: /logout
target: /login
access_control:
- { path: ^/secure_area, roles: ROLE_ADMIN }
routing.yml
register:
pattern: /register
defaults: { _controller: AcmeFOSUserBundle:Registration:register }
config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: Acme\FOSUserBundle\Entity\User
Я уверен, что spl_object_hash вызван registerAction в контроллере регистрации.
$user->setRoles(array('ROLE_USER'));
Здесь вы отправляете массив со строкой, но в классе User.php вы определили $ role как коллекцию объектов класса Role.php. Чтобы исправить это, вам нужно что-то вроде этого:
$user->addRole(new Role);
Вспомните, как создать метод addRole в вашем классе User.