Most of you should know that the "famous" article on " Writing a reliable PHP backend with Zend Framework " After reading the testimony, I decided to try it, because I could not find a solution to process my data.
Then I tried to write a skeleton view to have a concrete example.
But some points look strange to me. But I will talk about this later.
I deleted the code to be more clear. Here is the code:
class User
{
$_data = array('userId', 'userName');
public function __construct($data = null)
{
$this->populate($data);
}
public function populate($data = null)
{
if ( is_object ($data) )
{
$data = (array) $data;
}
if ( ! is_array($data) )
{
throw new Exception ('Data must be an array or an object');
}
foreach ($data as $property => $value)
{
$this->$property = $value;
}
}
public function toArray()
{
return $this->_data;
}
}
class UserTable extends Zend_Db_Adapter_Abstract
{
public function __construct ($options)
{
parent::__construct($options);
}
public function validateUser($user)
{
if ( null == $user->name || len($user->name) >= 30 || len($user->name) <= 0 )
{
throw new Zend_Db_Exception ('Username must be between 0 and 30 chars and must not be null');
}
$user->name = $this->quote($user->name);
return $user;
}
public function createUser(User $user)
{
$user = $this->validateUser($user);
$user = $user->toArray();
try
{
$this->insert('Users', $user);
$user->id $this->lastInsertId('Users');
} catch (Zend_Db_Expection $e) {
echo 'Error while creating user :', $e->getMessage();
}
return $user;
}
public function updateUser(User $user)
{
$user = $this->validateUser($user);
$user = $user->toArray();
if (null == $user->id)
{
throw new Exception ('User must have an userId to be updated');
}
try
{
$this->update('Users', $user, 'userId = ' . $user->id);
} catch (Zend_Db_Expection $e) {
echo 'Error while updating user :', $e->getMessage();
}
return $user;
}
}
class UserService
{
$_adapter = null;
public function __construct($adapter = null)
{
$this->setAdapter($adapter);
}
public function setAdapter($adapter = null)
{
$this->_adapter = $adaper;
}
public function getUserById($id = 0)
{
$this->getAdapter()->getUserById($id);
}
public function save(User $user)
{
if (null != $user->id)
{
$this->getAdapter()->createUser($user);
} else {
$this->getAdapter()->updateUser($user);
}
}
public function getPosts(User $user)
{
$postService = new PostService(new PostTable());
return $postService->getPostsByUser($user->id);
}
}
class UserController
{
protected $user = null;
public function init()
{
}
public function postsAction()
{
$userService = new UserService(new UserTable());
$this->view->posts = $userService->getPostsByUser($user->id);
}
}
So the last question: did I understand the concept? or did I make some mistakes implementing it?
PS: tag autocompletion didn’t work anymore, so I couldn’t provide the tags I needed.