Skip to content

Instantly share code, notes, and snippets.

@bdecarne
Forked from Ocramius/User.php
Created June 4, 2014 08:35
Show Gist options
  • Save bdecarne/0de4f569456a3d28a972 to your computer and use it in GitHub Desktop.
Save bdecarne/0de4f569456a3d28a972 to your computer and use it in GitHub Desktop.
<?php
namespace HelloWorld;
use InvalidArgumentException;
/**
* This class is somewhere in your library
* @Entity
* @Table(name="users")
*/
class User {
/**
* @var int
* @Id
* @Column(type="integer",name="id", nullable=false)
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @Column(type="string", length=255, name="login", nullable=false)
*/
protected $login;
/**
* @var UserGroup|null the group this user belongs (if any)
* @ManyToOne(targetEntity="HelloWorld\UserGroup", inversedBy="users")
* @JoinColumn(name="group_id", referencedColumnName="id")
*/
protected $group;
/**
* @param string $login
*/
public function __construct($login) {
$this->setLogin($login);
}
/**
* @return string
*/
public function getLogin() {
return $this->login;
}
/**
* @param string $login
*/
public function setLogin($login) {
$this->login = (string) $login;
}
/**
* @return HelloWorld\UserGroup|null
*/
public function getGroup() {
return $this->group;
}
/**
* Sets a new user group and cleans the previous one if set
* @param null|HelloWorld\UserGroup $group
*/
public function setGroup($group) {
if($group === null) {
if($this->group !== null) {
$this->group->getUsers()->removeElement($this);
}
$this->group = null;
} else {
if(!$group instanceof HelloWorld\UserGroup) {
throw new InvalidArgumentException('$group must be null or instance of HelloWorld\UserGroup');
}
if($this->group !== null) {
$this->group->getUsers()->removeElement($this);
}
$this->group = $group;
$group->getUsers()->add($this);
}
}
}
<?php
namespace HelloWorld;
use Doctrine\Common\Collections\Collection,
Doctrine\Common\Collections\ArrayCollection;
/**
* This class is somewhere in your library
* @Entity
* @Table(name="usergroups")
*/
class UserGroup {
/**
* @var int
* @Id
* @Column(type="integer",name="id", nullable=false)
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @Column(type="string", length=255, name="name", nullable=false)
*/
protected $name;
/**
* @var Collection
* @OneToMany(targetEntity="HelloWorld\User", mappedBy="group")
*/
protected $users;
/**
* @param string $name
*/
public function __construct($name) {
$this->users = new ArrayCollection();
$this->setName($name);
}
/**
* @return string
*/
public function getName() {
return $this->name;
}
/**
* @var string $name
*/
public function setName($name) {
$this->name = (string) $name;
}
/**
* @return Collection
*/
public function getUsers() {
return $this->users;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment