官术网_书友最值得收藏!

  • Mastering MongoDB 3.x
  • Alex Giamas
  • 266字
  • 2021-08-20 10:10:53

Doctrine ODM

Laravel is one of the most widely used MVC frameworks for PHP, similar in architecture to Django and Rails from the Python and Ruby worlds respectively. We will follow through configuring our models using a stack of Laravel, Doctrine, and MongoDB. This section assumes that Doctrine is installed and working with Laravel 5.x.

Doctrine entities are POPO (Plain Old PHP Objects) that, unlike Eloquent, Laravel's default ORM doesn't need to inherit from the Model class. Doctrine uses the Data Mapper pattern, whereas Eloquent uses Active Record. Skipping the get() set() methods, a simple class would look like:

use Doctrine\ORM\Mapping AS ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity
* @ORM\Table(name="scientist")
*/
class Scientist
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $firstname;
/**
* @ORM\Column(type="string")
*/
protected $lastname;
/**
* @ORM\OneToMany(targetEntity="Theory", mappedBy="scientist", cascade={"persist"})
* @var ArrayCollection|Theory[]
*/
protected $theories;
/**
* @param $firstname
* @param $lastname
*/
public function __construct($firstname, $lastname)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->theories = new ArrayCollection;
}
...
public function addTheory(Theory $theory)
{
if(!$this->theories->contains($theory)) {
$theory->setScientist($this);
$this->theories->add($theory);
}
}

This POPO-based model used annotations to define field types that need to be persisted in MongoDB. For example, @ORM\Column(type="string") defines a field in MongoDB with the string type firstname and lastname as the attribute names, in the respective lines.

There is a whole set of annotations available here http://doctrine-orm.readthedocs.io/en/latest/reference/annotations-reference.html . If we want to separate the POPO structure from annotations, we can also define them using YAML or XML instead of inlining them with annotations in our POPO model classes.

主站蜘蛛池模板: 阿拉尔市| 齐河县| 平顺县| 广平县| 淮滨县| 临城县| 锡林郭勒盟| 正阳县| 西畴县| 峨眉山市| 佛学| 高阳县| 闽清县| 连城县| 新余市| 宁阳县| 金门县| 周宁县| 塘沽区| 南投市| 兴义市| 溧水县| 香河县| 成武县| 紫阳县| 宁明县| 宣城市| 玛纳斯县| 沅江市| 仪征市| 酒泉市| 民权县| 天水市| 井冈山市| 千阳县| 漠河县| 云阳县| 静海县| 石门县| 富裕县| 岗巴县|