开发者

What is the structure of a (Data Access) Service Class

开发者 https://www.devze.com 2023-02-01 17:30 出处:网络
I learnt that I should be using service classes to persist entities into the database instead of putting such logic in models/controllers. I currently made my service class something like

I learnt that I should be using service classes to persist entities into the database instead of putting such logic in models/controllers. I currently made my service class something like

class Application_DAO_User {
    protected $user;
    public function __construct(User $user) {
        $this->user = $user
    }
    public function edit($name, ...) {
        $this->user->name = $name;
        ...
        $this->em->flush();
    }
}

I wonder if this should be the structure of a service class? where a service object represents a entity/model? Or maybe I should pass a User object everytime I want to do a edit like

public static function e开发者_开发技巧dit($user, $name) {
    $user->name = $name;
    $this->em->flush();
}

I am using Doctrine 2 & Zend Framework, but it shouldn't matter


I think you should first consider what you'd like to do with the user objects. For example if you only want to create, update and delete user records (CRUD) I can imagine this type of API:

<?php
public function create (array $data = null)
{
    $user = new User($data);
    $this->_persist($user)
         ->_flush();

    return $user;
}

public function update (User $user, array $data)
{
    foreach ($data as $name => $value) {
        $user->$name = $value;
    }

    $this->_flush();

    return $user;
}

public function delete (User $user)
{
    $this->_remove($user)
         ->_flush();
}

I seperated the methods to the entity manager, you can create something like below or skip the seperated methods at all. With these methods you could do additional checkups (for example if you want to persist there can be a check to look if the object is already persisted).

protected function _persist ($obj)
{
    $this->_em->persist($obj);
    return $this;
}

protected function _detach ($obj)
{
    $this->_em->detach($obj);
    return $this;
}

protected function _remove ($obj)
{
    $this->_em->remove($obj);
    return $this;
}

protected function _flush ()
{
    $this->_em->flush();
    return $this;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消