" " ( , , ).
, , .
- ActiveRecord, () create-update-delete. , . , , , update() .
- , AR- ( Doctrine, ORM..), .
...
interface Entity {
static function newEntity();
static function fetch($id);
function save();
function setProperties(array $properties);
function delete();
}
class Product implements Entity {
public $productId;
public $name;
public $price;
public $description;
public static function newEntity($id=NULL) {
$product = new Product();
$product->productId = $id;
return $product;
}
public static function fetch($id) {
if (!$row) {
return NULL;
}
$product = new Product();
$product->productId = $id;
$product->name = $row['name'];
$product->price = $row['price'];
$product->description = $row['description'];
return $product;
}
public function setProperties(array $properties) {
$this->name = $properties['name'];
$this->price = $properties['price'];
$this->description = $properties['description'];
}
public function save() {
}
public function delete() {
}
}
abstract class EntityCrudController {
protected $entityClass = 'UNDEFINED';
protected $editTemplate = NULL;
protected $templateEngine;
public function editAction($entityId) {
$entity = call_user_func($this->entityClass, 'fetch', $entityId);
$this->templateEngine->setTemplate($this->editTemplate);
$this->templateEngine->assign('entity', $entity);
return $this->template->render();
}
public function updateAction($entityId, array $formArray) {
$entity = call_user_func($this->entityClass, 'fetch', $entityId);
$entity->setProperties($formArray);
$entity->save();
$this->templateEngine->setTemplate($this->editTemplate);
$this->templateEngine->assign('entity', $entity);
$this->templateEngine->assign('message', 'Saved successfully!');
return $this->template->render();
}
}
class ProductCrudController extends EntityCrudController {
protected $entityClass = 'Product';
protected $editTemplate = 'editProduct.tpl';
}
$controller = new ProductCrudController();
$htmlOutput = $controller->editAction(1);
$htmlOutput = $controller->updateAction(1, array('name' => 'Test Product', 'price' => '9.99', 'description' => 'This is a test product'));
Of course, much can be improved. you usually do not want to make a request every time you call fetch () on an object, but instead request it once and save the resulting object in IdentityMap , which also ensures data integrity.
Hope this helps, it worked out a little more than I expected, but I think it is commendable that you are trying to solve this problem without creating a framework for this problem :)
source
share