I'm trying to persist a domain model to a DB without using an ORM just for fun.
It's pretty easy to persist properties, but I'm having hard time persisting a collection.
Let's say I have the following two objects.
class aModel
{
private $items = [];
public function __construct($id, $name, array $items = [])
{
$this->id = $id;
$this->name = $name;
$this->items = $items;
}
public function getId()
{
return $this->id;
}
public function getName()
{
return $this->name;
}
public function addItem(Item $item)
{
$this->items[] = $item;
}
}
class aDBRepository
{
public function persist(aModel $aModel)
{
$attributes = [
'id' => $aModel->getId(),
'name' => $aModel->getName()
];
$this->table->insert($attributes);
}
}
// Code
$aModel = new aModel("test id", "a name");
$aModel->addItem(new Item("id", "name"));
When I create a new aModel and add a new item to it, how do I detect 'unsaved' items and persist them?
I can only think of adding isSaved method in the Item class and loop through $items variable in aModel.
Without using reflection, what's the best way?
Related
Haven't found an answer yet but I'm sure there must be one: how do I prevent an object recursion/loop when objects reference each other? An example:
class Patient {
private $Issues = array();
[...]
public function __construct($id) {
[ Get data from DB ]
while ($row = $result->fetch_assoc()) {
$this->Issues[$row['idIssue']] = new Issue($row['idIssue']);
}
[...]
}
}
class Issue {
private $Patient;
[...]
public function __construct($id) {
[ Get data from DB ]
$this->Patient = new Patient($row['idPatient']); <-- Leads to recursion as the patient will load all it's Issues() etc. etc.
[...]
}
}
How do I prevent this? I could use the id of the Patient() instead of the real object but that feels like a hack. Is there a way to use the real object?
Do not recreate object. Just pass the instance of the master object to the detail constructor. E.g.:
class Patient {
private $Issues = array();
[...]
public function __construct($id) {
[ Get data from DB ]
while ($row = $result->fetch_assoc()) {
$this->Issues[$row['idIssue']] = new Issue($row['idIssue'], $this);
}
[...]
}
}
class Issue {
private $Patient;
[...]
public function __construct($id, Patient $patient) {
[ Get data from DB ]
$this->Patient = $patient
[...]
}
}
You can (should !) separate the DB connection/queries from the entities definitions and pass references to relations, otherwise, you can't mock entities, plus mixing DB connection and entities definition goes against the separation of concerns :
// somewhere in your code
$idPatient = 42;
$patient = new Patient();
$patient->setId($idPatient);
// get datas from DB
while ($row = $result->fetch_assoc())
{
$issue = new Issue();
$issue->setId($row['idIssue'])
->setPatient($patient);
$patient->addIssue($issue);
// or, shorter way :
// $patient->addIssues((new Issue())->setId($row['idIssue'])
// ->setPatient($patient));
}
class Patient {
private $Issues = array();
private $Id;
public function addIssue(Issue $issue): self
{
$this->Issues[] = $issue;
return $this;
}
public function setId(int $id): self
{
$this->Id = $id;
return $this;
}
}
class Issue {
private $Patient;
private $Id;
public function addPatient(Patient $patient): self
{
$this->Patient = $patient;
return $this;
}
public function setId(int $id): self
{
$this->Id = $id;
return $this;
}
}
I'm trying to figure out the best way to iterate over an object's properties so I can build a sql query for an insert or update. I also am looking to be able to omit certain fields in the iteration.
Below is an example object where I would like to grab name and age but omit employer because that is a join from another table.
class person
{
private $_name, $_age, $_employer;
public function get_name()
{
return $this->_name;
}
public function get_age()
{
return $this->_age;
}
public function get_employer()
{
return $this->_employer;
}
}
I could cast an object as an array to get the properties but I still don't have a good way to omit certain properties.
$personObj = new person();
foreach((array)$personObj as $k => $v)
{
$sql .= "...";
}
Hope this gives you a hint
class person
{
private $_name = 'dude';
private $_age = '27';
private $_employer = 'yes';
public function get_name()
{
return $this->_name;
}
public function get_age()
{
return $this->_age;
}
public function get_employer()
{
return $this->_employer;
}
}
$person = new person();
$required = array('name','age');
foreach($required as $req)
{
$func = "get_{$req}";
echo $person->$func();
}
https://3v4l.org/vLdAN
There are lots of articles regarding factory method implementation in PHP.
I want to implement such a method for my MongoDB implementation in PHP.
I wrote the code something like below. Please Look at that code.
<?php
class Document {
public $value = array();
function __construct($doc = array()) {
$this->value = $doc;
}
/** User defined functions here **/
}
class Collection extends Document {
//initialize database
function __construct() {
global $mongo;
$this->db = Collection::$DB_NAME;
}
//select collection in database
public function changeCollection($name) {
$this->collection = $this->db->selectCollection($name);
}
//user defined method
public function findOne($query = array(), $projection = array()) {
$doc = $this->collection->findOne($query, $projection);
return isset($doc) ? new Document($doc) : false;
}
public function find($query = array(), $projection = array()) {
$result = array();
$cur = $this->collection->find($query, $projection);
foreach($cur as $doc) {
array_push($result, new Document($doc));
}
return $result;
}
/* Other user defined methods will go here */
}
/* Factory class for collection */
class CollectionFactory {
private static $engine;
private function __construct($name) {}
private function __destruct() {}
private function __clone() {}
public static function invokeMethod($collection, $name, $params) {
static $initialized = false;
if (!$initialized) {
self::$engine = new Collection($collection);
$initialized = true;
}
self::$engine->changeCollection($collection);
return call_user_func_array(array(self::$engine, $name), $params);
}
}
/* books collection */
class Books extends CollectionFactory {
public static function __callStatic($name, $params) {
return parent::invokeMethod('books', $name, $params);
}
}
/* authors collection */
class Authors extends CollectionFactory {
public static function __callStatic($name, $params) {
return parent::invokeMethod('authors', $name, $params);
}
}
/* How to use */
$books = Books::findOne(array('name' => 'Google'));
$authors = Authors::findOne(array('name' => 'John'));
Authors::update(array('name' => 'John'), array('name' => 'John White'));
Authors::remove(array('name' => 'John'));
?>
My questions are:-
Is this correct PHP implementation of Factory method?
Does this implementation have any issues?
Are there any better methodologies over this for this scenario?
Thanks all for the answers.
Hmm no, because with your piece of code you make ALL methods on the collection class available for a static call. That's not the purpose of the (abstract) factory pattern.
(Magic) methods like __callStatic or call_user_func_array are very tricky because a developer can use it to call every method.
What would you really like to do? Implement the factory pattern OR use static one-liner methods for your MongoDB implementation?!
If the implementation of the book and author collection has different methods(lets say getName() etc..) I recommend something like this:
class BookCollection extends Collection {
protected $collection = 'book';
public function getName() {
return 'Book!';
}
}
class AuthorCollection extends Collection {
protected $collection = 'author';
public function getName() {
return 'Author!';
}
}
class Collection {
private $adapter = null;
public function __construct() {
$this->getAdapter()->selectCollection($this->collection);
}
public function findOne($query = array(), $projection = array()) {
$doc = $this->getAdapter()->findOne($query, $projection);
return isset($doc) ? new Document($doc) : false;
}
public function getAdapter() {
// some get/set dep.injection for mongo
if(isset($this->adapter)) {
return $this->adapter;
}
return new Mongo();
}
}
class CollectionFactory {
public static function build($collection)
{
switch($collection) {
case 'book':
return new BookCollection();
break;
case 'author':
return new AuthorCollection();
break;
}
// or use reflection magic
}
}
$bookCollection = CollectionFactory::build('book');
$bookCollection->findOne(array('name' => 'Google'));
print $bookCollection->getName(); // Book!
Edit: An example with static one-liner methods
class BookCollection extends Collection {
protected static $name = 'book';
}
class AuthorCollection extends Collection {
protected static $name = 'author';
}
class Collection {
private static $adapter;
public static function setAdapter($adapter) {
self::$adapter = $adapter;
}
public static function getCollectionName() {
$self = new static();
return $self::$name;
}
public function findOne($query = array(), $projection = array()) {
self::$adapter->selectCollection(self::getCollectionName());
$doc = self::$adapter->findOne($query, $projection);
return $doc;
}
}
Collection::setAdapter(new Mongo()); //initiate mongo adapter (once)
BookCollection::findOne(array('name' => 'Google'));
AuthorCollection::findOne(array('name' => 'John'));
Does it make sense for Collection to extend Document? It seems to me like a Collection could have Document(s), but not be a Document... So I would say this code looks a bit tangled.
Also, with the factory method, you really want to use that to instantiate a different concrete subclass of either Document or Collection. Let's suppose you've only ever got one type of Collection for ease of conversation; then your factory class needs only focus on the different Document subclasses.
So you might have a Document class that expects a raw array representing a single document.
class Document
{
private $_aRawDoc;
public function __construct(array $aRawDoc)
{
$this->_aRawDoc = $aRawDoc;
}
// Common Document methods here..
}
Then specialized subclasses for given Document types
class Book extends Document
{
// Specialized Book functions ...
}
For the factory class you'll need something that will then wrap your raw results as they are read off the cursor. PDO let's you do this out of the box (see the $className parameter of PDOStatement::fetchObject for example), but we'll need to use a decorator since PHP doesn't let us get as fancy with the Mongo extension.
class MongoCursorDecorator implements MongoCursorInterface, Iterator
{
private $_sDocClass; // Document class to be used
private $_oCursor; // Underlying MongoCursor instance
private $_aDataObjects = []; // Concrete Document instances
// Decorate the MongoCursor, so we can wrap the results
public function __construct(MongoCursor $oCursor, $sDocClass)
{
$this->_oCursor = $oCursor;
$this->_sDocClass = $sDocClass;
}
// Delegate to most of the stock MongoCursor methods
public function __call($sMethod, array $aParams)
{
return call_user_func_array([$this->_oCursor, $sMethod], $aParams);
}
// Wrap the raw results by our Document classes
public function current()
{
$key = $this->key();
if(!isset($this->_aDataObjects[$key]))
$this->_aDataObjects[$key] =
new $this->sDocClass(parent::current());
return $this->_aDataObjects[$key];
}
}
Now a sample of how you would query mongo for books by a given author
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoCollection($db, 'book');
// search for author
$bookQuery = array('Author' => 'JR Tolken');
$cursor = $collection->find($bookQuery);
// Wrap the native cursor by our Decorator
$cursor = new MongoCursorDecorator($cursor, 'Book');
foreach ($cursor as $doc) {
var_dump($doc); // This will now be an instance of Book
}
You could tighten it up a bit with a MongoCollection subclass and you may as well have it anyway, since you'll want the findOne method decorating those raw results too.
class MongoDocCollection extends MongoCollection
{
public function find(array $query=[], array $fields=[])
{
// The Document class name is based on the collection name
$sDocClass = ucfirst($this->getName());
$cursor = parent::find($query, $fields);
$cursor = new MongoCursorDecorator($cursor, $sDocClass);
return $cursor;
}
public function findOne(
array $query=[], array $fields=[], array $options=[]
) {
$sDocClass = ucfirst($this->getName());
return new $sDocClass(parent::findOne($query, $fields, $options));
}
}
Then our sample usage becomes
$m = new MongoClient();
$db = $m->selectDB('test');
$collection = new MongoDocCollection($db, 'book');
// search for author
$bookQuery = array('Author' => 'JR Tolken');
$cursor = $collection->find($bookQuery);
foreach($cursor as $doc) {
var_dump($doc); // This will now be an instance of Book
}
I have a database with authors and books, m:n
authors (a_id, ...)
authors_books (a_id, b_id)
books (b_id, ...)
My problem is, that I can't use the constructors to fetch the author/book-data into an array, because I would get an infinite loop.
class Book
{
public $name;
public $authors;
public function __construct($name)
{
$this->name=$name;
$this->authors=$this->Get_Authors();
}
public function Get_Authors()
{
$authors=array();
/* ... (database) */
$authors[]=new Author($name_from_db);
return $authors;
}
}
class Author
{
public $name;
public $books;
public function __construct($name)
{
$this->name=$name;
$this->books=$this->Get_Books();
}
public function Get_Books()
{
$books=array();
/* ... (database) */
$books[]=new Book($name_from_db);
return $books;
}
}
Example:
new Book('book_1');
-> is going to fetch 'author_1' and uses __constructor of Author class
new Author('author_1');
-> is going to fetch 'book_1 and uses __constructor of Book class
...
What is the "best practice" to resolve a m:n relation in PHP classes?
You can use lazy loading here:
class Book {
public $name;
private $_authors = null;
public function __constructor($name) {
$this->name = $name;
}
public function getAuthors() {
if ($this->_authors === null) {
$this->_authors = array();
/* database */
$this->_authors[] = new Author(/**/);
}
return $this->_authors;
}
// You can add some magic getter if you want to access authors as property
public function __get($key) {
if ($key === 'authors') {
return $this->getAuthors();
}
throw new Exception('Unknown property '.$key);
}
}
class Authors {
public $name;
private $_books = null;
public function __constructor($name) {
$this->name = $name;
}
public function getBooks() {
if ($this->_books === null) {
$this->_books = array();
/* database */
$this->_books[] = new Book(/**/);
}
return $this->_books;
}
// You can add some magic getter if you want to access books as property
public function __get($key) {
if ($key === 'books') {
return $this->getBooks();
}
throw new Exception('Unknown property '.$key);
}
}
This will cause that authors/books will be loaded only if you'll need it and won't loop infinitely, but you can reach another problem here:
$author = new Author("Jon Doe");
$book = $author->books[0];
// assuming that book has one author
// $book->authors[0] will not be same object as $author
Solution for that would be to use some third object for loading books and authors, that will store already loaded objects and inject them in proper places
class Library {
private $_books = array();
private $_authors = array();
public function getBooksForAuthor($authorId) {
/* db query... */
$books = array();
while ($row = $stmt->fetch()) {
if (isset($this->_books[$row['id']]) {
$books[] = $this->_books[$row['id']];
} else {
$book = new Book($row);
$this->_books[$row['id']] = $book;
$books[] = $book;
}
}
return $books;
}
/* and similar authorsForBook() method */
}
class Author {
private $_data;
private $_library;
private $_books = null;
public function __constructor($data, $library) {
$this->_data = $data;
$this->_library = $library;
}
public function getBooks() {
if ($this->_books === null) {
$this->_books = $this->_library->getBooksForAuthor($this->_data['id']);
}
return $this->_books;
}
public function __get($key) {
if ($key === 'books') {
return $this->getBooks();
}
if (isset($this->_data[$key]) {
return $this->_data[$key];
}
throw new Exception('Unknown property '.$key);
}
}
/* and similar for book */
Why do you want to load all related object? Use "lazy loading"- don't load all related objects until you need them. In your case it would mean getting related object through their getter method. If you need to get them through property you can implement getters through magic methods.
I have an action in my controller called createAction. I also have a model My_Application_Product, that I'm using to create the product within the system. I'm following the Architecting Your Models talk. Is this the "correct" way to save my product? Code for My_Application_Product follows below.
class ProductController extends Zend_Controller_Action {
public function createAction() {
$categoryAdapter = new Application_Model_Categories();
$categories = $categoryAdapter->fetchAll('parent_id IS NOT NULL');
$form = new My_Application_Forms_Product_Create();
$category = $form->getElement('category');
foreach ($categories as $cat) {
$category->addMultiOption($cat->id, $cat->name);
}
if ($this->getRequest()->isPost()) {
if (! $form->isValid($_POST)) {
$this->view->form = $form;
return $this->render('create');
}
$product = new My_Application_Product();
$product->name = $_POST['name'];
$product->company_id = 1;
$product->category_id = $_POST['category'];
$product->trade_names = $_POST['trade_names'];
$product->website = $_POST['website'];
$product->description = $_POST['description'];
$product->closed_loop = $_POST['closed_loop'];
$product->sold_as = $_POST['sold_as'];
$product->sold_in = $_POST['sold_in'];
$product->dilution = $_POST['dilution'];
$id = $product->save();
$url = $this->getHelper('Url')
->url(array('action' => 'registryservices', 'id' => $id));
$this->_redirect($url);
}
$this->view->form = $form;
}
}
'
class My_Application_Product implements My_Application_Product_Interface {
// declare all the internally used variables here.
// if something isn't showing up when trying to save, that's probably
// because it's missing from here
protected $_id;
protected $_name;
protected $_company_id;
protected $_trade_names;
protected $_website;
protected $_description;
protected $_closed_loop;
protected $_sold_as;
protected $_sold_in;
protected $_dilution;
protected $_category_id;
protected $_verification_level;
protected $_dfe_sccp;
protected $_dfe_siicp;
protected $_el_ccd_hsc;
public function __set($name, $value) {
$local_var_name = "_" . $name;
if (property_exists($this, $local_var_name)) {
$this->{$local_var_name} = $value;
}
}
public function __get($name) {
$local_var_name = "_" . $name;
if (property_exists($this, $local_var_name)) {
return $this->{$local_var_name};
}
}
/**
*
* #param array $data The data to save
*/
public function save() {
// this means we're editing something
if ($this->id) {
$table = new My_Application_Product_Table();
$data = $table->find($this->id)->toArray();
$data = $data[0];
foreach (get_class_vars(get_class($this)) as $key => $value) {
if (! is_null($this->$key)) {
$data[preg_replace('/^_/', '', $key)] = $this->$key;
}
}
$id = $table->update($data, sprintf('id = %d', $this->id));
// this means we're creating, and this is the data we need
} else {
$data = array(
'id' => rand(1,1000000),
'name' => $this->name,
'date_created' => date('Y-m-d H:i:s'),
);
$id = $table->insert($data);
}
return $id;
}
}
'
class My_Application_Product_Table extends Zend_Db_Table_Abstract {
protected $_name = 'products';
protected $_primary = 'id';
}
Split your model in multiple classes :
1 class representing the entity (no methods, except for accessors).
this class represents your "real-life" object, and is just a structured data container, which encapsulates data
class My_Application_Model_Product {
protected $_id;
protected $_name;
protected $_company_id;
protected $_trade_names;
protected $_website;
//...
public function __set($name, $value) {
//Implement your setter here
}
public function __get($name) {
}
}
1 class responsible of data mapping.
This class makes is the link between your data source (database, webservice, file...) and your entity.
Class My_Application_Model_DataMapper_Product {
protected $_adapter
public function __construct($adapter)
{
$this->setAdapter($adapter);
}
public function setAdapter($adapter)
{
$this->_adapter = $adapter;
}
public function save(My_Application_Model_Product $product)
{
//Perform your save operation here
}
public function fetchAll()
{
}
public function findById($id)
{
}
//You may implement specific methods for any needed specific operation (search, bulk-update...
}
a third class for data access and persistence (Zend_Db_table, Soap client...) This third class is passed to the datamapper as the adapter and is used inside the methods to getch/save data.
With this architecture, you have a clear separation of responsibilities, and may change one part without affecting the other : for example, you could switch from a database to a webservice without affecting your Product class.
A very simple example is given in the zf Quickstart