I'm trying to decide whether to create many classes for each content type I have in my application/database or just stick with procedural code.
Version 1:
make a class for each object collection:
class App{
protected $user_collection;
function getUserCollection(){
if(!isset($this->user_collection)
$this->user_collection = new UserCollection($this);
return $this->user_collection;
}
// ...
}
class UserCollection{
function __construct(App $app){
$this->app = $app;
}
function getUser($user){
return new User($this->app, $user);
}
function getUsers($options){
$users = $this->app->getDatabase()->query($options);
foreach($users as &$user)
$user = new User($this, $user);
return $users;
}
// ...
}
which I'm using like:
$app = new App();
echo $app->getUserCollection()->getUser('admin')->email_address;
version 2:
keep all methods in a single class
class App{
function getUsers($options){
$users = $this->getDatabase()->query($options);
foreach($users as &$user)
$user = new User($this, $user);
return $users;
}
function getUser($user){
return new User($this, $user);
}
// ...
}
used like:
$app = new App();
echo $app->getUser('admin')->email_address;
version 3:
make getUsers() a a static method in the "User" class (the method instantiates a new User object):
$app = new App();
echo User::getUser($app, 'admin')->email_address;
Which way should I go? The "user" object is just an example, App has other objects too, like "database", "pages" etc.
I would use your version 1, but I would make getUser() and getUsers() methods of App.
This gets rid of the awkward getUserCollection() call, because instead inside the getUser() and what not you just call $this->user_collection.
Personnaly, I often used the second one with method like this:
class user {
/**
* Load object from ...
*/
public function load($userId) {}
/**
* Insert or Update the current object
*/
public function save() {}
/**
* Delete the current object
*/
public function delete() {
// delete object
// Reset ID for a future save
$this->UserID = null;
}
/**
* Get a list of object
*/
public static function getList() {
// Make your search here (from DB)
// Put rows into new "SELF" object
$list = array();
foreach($rows as $row) {
$obj = new self();
$obj->populate($row);
$list[$obj->UserID] = $obj; // Associative array or not...
}
}
}
Like you can see, I set my "getList" function static to simply access like this:
$listUsers = user::getList();
OK, it's very simple but work in most case of simple app.
Related
I have two classes, with one storing multiple references to the other. After I create a new instance of the second class, I might have to change properties on it later and I would like it to update all references to that object. Is there a way to make the object instances always pass by reference so that when a property gets updated in the object it also updates all other references to it?
class Users {
private $members = array();
public function addMember($id) {
$member = new Member($id);
array_push($members, $member);
return $member;
}
}
class User {
public $id;
__construct($id) {
$this->id = $id;
}
public function addProperty($propName, $propValue) {
$this->{$propName} = $propValue;
}
}
So currently with this setup I can create a new member and add them to the members array:
$users = new Users();
$user = $users->addMember(1);
But if I try to add a new property to the member as so:
$member->addProperty("job_title", "developer");
The property doesn't appear in the members array because the member is not being passed by reference.
See this:
public function addMember($id) {
$member = new Member($id);
....
Here you create an object of class Member, but I think you want
$member = new User($id);
Because of unit testing our classes looks like this:
class MyObserverClass
{
private $model;
public function __construct(Model $model)
{
$this->model= $model;
}
public function saved(OtherModel $otherModel)
{
//Some condition
while(...) {
//$this->model->exists = false;
$this->model->property = "x-value";
$this->model->sub_id = $otherModel->id;
//Other props...
$this->model->state = model::STATE;
$this->model->save();
}
}
But when I run this, the same model get overridden x times, and only the last one will be in the database.
How I can force laravel to save the model as a new one in the database? I was trying with the exists property but I couldn't make it work.
You can use newInstance method to create new object instance:
while(...) {
$model = $this->model->newInstance();
$model->property = "x-value";
$model->sub_id = $otherModel->id;
//Other props...
$model->state = model::STATE;
$model->save();
}
However if you create many same or similar object in this loop, you could use replicate method to create one base object and to change only some properties.
try this
while(...) {
$model = new self;
$model -> name = $name;
....
$model -> save();
}
or you can pass an array to insert to create method
// Create a new user in the database...
$user = Model::create(['name' => 'John']);
I'm developing an Apigility driven application based on the Zend Framework 2.
Currently I'm sending the data retrieved in the database directly to the client: a request comes in, the MyResource#fetch(...) or MyResource#fetchAll(...) gets triggered and calls an appropriate method on MyService class, that calls MyMapper to retireve the data with its methods like findFooByBar(...).
Now I'd like to process the data, before the response is sent. How can I do that?
The Apigility ZF HAL documentation shows, how to access the entity data between it has been retrieved and sent to the client. Well I tried this out. It's ugly and to much code for such task. And... it doesn't work. I want however post here my attept:
namespace Portfolio;
...
class Module implements ApigilityProviderInterface {
private $serviceManager;
public function onBootstrap(MvcEvent $event) {
$application = $event->getTarget();
$this->serviceManager = $serviceManager = $application->getServiceManager();
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$hal = $viewHelperManager->get('Hal');
$hal->getEventManager()->attach('renderEntity', array($this, 'onRenderEntity'));
$hal->getEventManager()->attach('renderCollection', array($this, 'onRenderCollection'));
}
public function onRenderEntity($event) {
$entity = $event->getParam('entity');
if ($entity->entity instanceof ProjectEntity) {
$projectEntity = $entity->entity;
$imageCollection = $this->tempCreateimagesForProject(
$event, $entity->entity->getId()
);
$projectEntity->setImages($imageCollection);
$event->setParam('entity', $projectEntity);
}
}
public function onRenderCollection($event) {
$collection = $event->getParam('collection');
$projectCollection = $collection->getCollection();
if ($projectCollection instanceof ProjectCollection) {
foreach ($projectCollection as $key => $projectItem) {
$tempProject = $projectCollection->getItem($key);
$tempProject->append(
['images' => $this->tempCreateimagesForProject($tempProject->offsetGet('id'))]
);
$projectCollection->getItem($key)->offsetSet($key, $tempProject);
}
}
}
private function tempCreateimagesForProject(Event $event, $projectId) {
$imageService = $this->serviceManager->get('Portfolio\V2\Rest\ImageService');
$imageCollection = $imageService->getImagesForProject($projectId);
return $imageCollection;
}
...
}
I think using the renderEntity and renderCollection events is not the correct spot to add this kind of resource specific logic. It is more suitable for more general changes or incidental customization.
You can add this logic to your resource listeners. So in your fetch and fetchAll methods in your MyResource class you can add the custom code you currently added in these onRenderEntity and onRenderCollection methods.
So something like this:
class MyResource extends AbstractResourceListener
{
/**
* Your image service dependency
*/
protected $imageService;
/* ... */
public function fetch($id)
{
$project = $this->projectMapper->fetch($id);
$imageCollection = $this->imageService->getImagesForProject($project);
$project->setImages($imageCollection);
return $project;
}
/* ... */
public function fetchAll($params = array())
{
$projects = $this->projectMapper->fetchAll();
foreach ($projects as $key => $project) {
$imageCollection = $this->imageService->getImagesForProject($project);
$project->setImages($imageCollection);
}
return $projects;
}
/* ... */
}
One possible solution is handling the data in the Hydrator. So we write a custom Hydrator class and enrich the items with nested objects and lists in it. It can look like this:
Portfolio\V2\Rest\Project\ProjectHydrator
...
class ProjectHydrator extends ClassMethods {
/**
* #var ImageService
*/
protected $imageService;
...
/*
* Doesn't need to be implemented:
* the ClassMethods#hydrate(...) handle the $data already as wished.
*/
/*
public function hydrate(array $data, $object) {
$object = parent::hydrate($data, $object);
if ($object->getId() !== null) {
$images = $this->imageService->getImagesForProject($object->getId());
$object->setImages($images);
}
return $object;
}
*/
/**
* #see \Zend\Stdlib\Hydrator\ClassMethods::extract()
*/
public function extract($object) {
$array = parent::extract($object);
if ($array['id'] !== null) {
$images = $this->imageService->getImagesForProject($array['id']);
$array['images'] = $images;
}
return $array;
}
}
It's not a nice solution, since then a part of the model / data retrieving logic gets moved to the hydrator. But it works. Here is shown an implementation of this approach and here is a discussion to this topic on GitHub.
If you are using the ClassMethods Hydrator and your Collection extends \Zend\Paginator\Paginator a good solution without losing the Collection's consistency and not changing anybody's code is to overwrite your getCurrentItems() method.
public class MyResourceCollection // most likely extends Paginator
{
public function getCurrentItems()
{
// getting the original items
$items = parent::getCurrentItems();
// as we work with objects $item will be an object
// when working with objects we use references to them not clones of objects
// so changes to $item are also present in the collection
foreach ($collection as $item) {
$oldSomething = $item->getSomething();
$item->setSomething('['.$oldSomething.']');
}
// $items are now changed, return them
return $items;
}
}
I have named the key something not to get confused with the getValue method from other places.
This makes the something value look like [something].
I am wondering whether or not it is possible to elegantly map the results of a PDO query to an array member in a class rather than have them floating about as public properties of that object.
Say I have the (condensed) following:
class DBObject {
protected
$record = array();
function __construct(array $record) {
if(!empty($record)) {
$this->loadRecord($record);
}
}
}
Ideally, I want to call the constructor with an array of values passed from the database, rather than use __set or any other weird methods. So using PDO's existing API would be great.
My rough get_all function at the moment has got this far:
static function get_all() {
$class = get_called_class();
$results = DB::factory()->query('SELECT * FROM ' . $class . ' ORDER BY ID');
$results->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, $class);
return $results;
}
NB: I'm running PHP 5.3 and MySQL through PDO, and already know this problem is solveable using __set, but I explicitly want to avoid using it in favour of something more performant.
You don't need to pass arguments to a constructor to make a class with private members using PDO::FETCH_CLASS. You can do something like this:
<?php
class Songs
{
private $artist;
private $title;
public function __construct()
{
}
public function get_artist()
{
return $this->artist;
}
public function get_title()
{
return $this->title;
}
private function set_artist($artist)
{
$this->artist = $artist;
}
private function set_title($title)
{
$this->title = $title;
}
}
I'm actually doing that on a demo site that I built. It works just fine with PDO::FETCH_CLASS. By default, FETCH_CLASS creates objects by populating the fields BEFORE the constructor. Think of it as bypassing the constructor. And it will do this with private members.
If you'd rather pass arguments to the constructor you can do your query like this:
$obj = $statement->fetchALL(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Songs', $params);
In that case your constructor would look like this:
public function __construct($params)
{
$this->artist = $params[0]['artist'];
$this->title= $params[0]['title'];
}
Removed previous code
Right, can't you do something like this:
class DBObject {
protected $record = array();
function __construct($record = null) {
if(null === $record){
$obj_vars = get_object_vars($this);
$cls_vars = get_class_vars(get_class($this));
$this->$record = array_diff_key($obj_vars, $cls_vars);
}else{
$this->record = $record;
}
}
}
The problem with this however is that the values are still available as public members.
But what it will do is compare 'pre-defined' (class) members to the actual (object) members.
Since PDO will create new members in the object you can use array_diff_key to get the 'new' members.
Yes, this will still not pass them through your constructor.
How about using magic __set() method:
<?php
class MyClass
{
protected $record = array();
function __set($name, $value) {
$this->record[$name] = $value;
}
}
$pdo = new PDO("mysql:host=localhost;dbname=db", 'user', 'password');
$results = $pdo->query('SELECT * FROM table');
$results->setFetchMode(PDO::FETCH_CLASS, 'MyClass');
PHP will call this magic method for every non-existent property passing in its name and value.
I have some expierence in PHP, but have no one in application architecture
Now I want to orginize my own "bicycle". It's something not useful, maybe mini-framework or mini-application, I want get some exp here.
I need now to write classes for work with database and classese for entities (one of them isUser)
I have following code for database (some cheks and method are omitted to minify this question):
namespace DataBase;
class DataBase {
/**
*
* #var \PDO $pdo
*/
public $pdo;
public function __construct($host, $dbname, $username, $password=''){
$this->pdo = new \PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password,
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
}
/**
*
* #param string $statement
* #return Statement
*/
public function prepare($statement){
return new Statement($this->pdo->prepare($statement));
}
}
namespace DataBase;
class Statement {
private $stmt;
public function __construct(\PDOStatement $stmt) {
$this->stmt = $stmt;
}
public function query() {
try {
$this->stmt->execute();
return $this; //for chaining
}
public function bind($key, $value) {
$this->stmt->bindValue($key, $value, $this->typeof($value));
return $this; //for chaining
}
//some methods for fetching data(works with fetch,fetchAll, fetchColumn and different PDO::FETCH_ methods
public function fetchUpdate($obj) {
$this->stmt->setFetchMode(\PDO::FETCH_INTO, $obj);
$this->stmt->fetch();
}
public function fetchRow() {
return $this->stmt->fetch(\PDO::FETCH_OBJ);
}
public function fetchRowClass($class) {
return $this->stmt->fetchObject($class);
}
}
And Some dummy for User class
<?php
/**
* Description of User
*
* #author riad
*/
class User {
private $id;
private $name = null;
private $status = null;
private $hasInfo = false;
private static $cache=array();
public function __construct() {
}
public function getId() {
return $this->id;
}
public function getName() {
if(!$this->hasInfo)
$this->getInfo ();
return $this->name;
}
public function isAuthorized(){
return $this->status!="noauth";
}
public static function createById($id) {
// I want this method to cerate user from id, then get info only I will use it after that
if(array_key_exists($id,self::$cache)){
return self::$cache[$id];
}
$user = new User;
$user->id = $id;
return $user;
}
private function getInfo(){
try{
\FrontController::getInstance()->getDB()->
prepare('SELECT * FROM `users` WHERE `id`=:id')->
bind('id', $this->id)->query()->fetchUpdate($this);
$this->hasInfo = true;
}
catch(\DataBase\NotFoundException $dbe){
$this->status = "deleted";
}
}
public static function createFromRequest($request){
$user = new User;
try{
//try get data from cookie
\FrontController::getInstance()->getDB()->
prepare('SELECT * FROM `users` WHERE `session` = :session AND `id`= :id')->
bind('id', $id)->bind('session',$session)->query()->
fetchUpdate($user);
}
catch(... $e){
$user->status = "noauth";
$user->id = 0;
// make it unregged
}
return $user;
}
}
?>
I have some problems with it.
I don't want set properties from database, that are not listed in props of class list(is not so important, of course). I know that I can use public function __call($name,$value){
//do nothing;
}
I want to mkae this props private, but want also use $stmt->fetchUpdate($obj) I know I can use public function __call($name,$value){
$this->$name=$value;
}, but it's as declare props public and it is on the road with first point
I can also use public function __call($name,$value){
if($name=='id'){
$this->id=$value;
}
else if($name=='status'){
$this->status=$value;
}
} But it's not comfortable to write it for every entity class and not save as from publicity of this methods
I want to set $this->hasInfo to true when I get this class from database. I know I can change my Database class to always set some variable to true when by default it's false. But it seems to be not elegant.
I want to update cache when I set id (It maybe used as previos point)
Is it possible to avoid fetchRowClass write direct to props and use setter as with fetchUpdate? Or maybe allow fetchUpdate direct access?
I know I write a lot of code self but I want your opinion:
What should I improve?
What are other/the best possible solution for problems from previos list?
Hope, It's not so hard to read and understand.
Glad to see any suggestions
With regards Alex
Few tips: [based on my own experience and frameworks i already used]
Basically what you should/want/might do is to create a SuperClass for all the clases in you model. This class will contain the reference to the Database Instance, and it will have all the common methods for your model, i.e. getById($id), getAll(),getPaginated(), etc.
The other goal of this SuperClass is to map the results from the database into Instances of your Model's Classes. So in the end, your user class would have only properties, accessors and methods that are specific to the class, like special queries or something like that.
Here's an example of what this could look like:
Class Model{
protected function getById($_id){
$_table = get_class($this);
$anonymous = $this->_getObjectById($_table,$_id); //this method will execute a query (unsing PDO) and return a StdClass object with the results
$this->mapTable($anonymous,$_table); //this method will take the StdClass instance and will transform it into a $_table Instance
}
private function mapTable($stdInstance,$model_name){
foreach($stdInstance as $key => $value){
try{
if(property_exists($this,$key)){
$this->$key = $value; //you could declare the model's properties as protected... or you could create accessors and call them here
}
} catch(Exception $ex) {
/* something went wrong o_O */
}
}
Class User extends Model{
protected $id;
protected $name;
.....
}
Class Controller{
public function index(){
$user = new User();
$user->getById($_GET['id']);
print_r($user);
//now you can pass the $user object to the View to display it
}
}
in a few words... the Model class is a very small ORM. You could try to create your own ORM, (like i did) but you'll face a lot of problems when trying to map the relations between objects: Nx1,1xN,NxN,1x1, inheritance, "deeper relations" and the n+1 problem. You'll also need to, somehow, define the model structure so your ORM could understand it, maybe using YAML/XML files or reading the structure directly from the table structure of your databe, or having a naming convention in your properties...
its a really interesting field :)
Hope this helps and Good Luck