Zend Framework2 会员管理项目之三: 建立数据模型及显示用户列表

2014年03月05日

这篇博客主要通过zf完成用户一览显示的功能

2014-03-05-01

编辑 module/Member/src/Member/Model/User.php文件

这就是数据库表users的模型类文件,exchangeArray函数将表单传过来的用户信息数据转变为user的成员数据。

<?php
/**
 * This source file is part of Qiai.
 *
 * PHP Version >=5.3
 *
 * @category   Qiai_Application
 * @package    Member
 * @subpackage Model
 * @author     Sai (QIAI) <sai@qiais.com>
 * @license    Qiai-License http://www.qiai.com/licenses/qiai.ck.html
 * @link       http://www.qiais.com
 */

namespace Member\Model;

/**
 * User model
 *
 * @category   Gc_Application
 * @package    Member
 * @subpackage Model
 */
class User
{
    public $id;
    public $name;
    public $email;
    public $password;
    public $role;
    public $tel;
    public $fax;
    public $mobile;
    public $zipcode;
    public $address;
    public $created;

    /**
     * set password
     *
     * @param string $plain_password plain key
     *
     * @return void
     */
    public function setPassword($plain_password)
    {
        $this->password = sha1($plain_password);
    }

    /**
     * change form data to members of Member
     *
     * @param array $data form data
     *
     * @return void
     */
    function exchangeArray($data)
    {
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->name = (isset($data['name'])) ? $data['name'] : null;
        $this->email = (isset($data['email'])) ? $data['email'] : null;
        $this->role = (isset($data['role'])) ? $data['role'] : null;
        $this->tel = (isset($data['tel'])) ? $data['tel'] : null;
        $this->mobile = (isset($data['mobile'])) ? $data['mobile'] : null;
        $this->fax = (isset($data['fax'])) ? $data['fax'] : null;
        $this->zipcode = (isset($data['zipcode'])) ? $data['zipcode'] : null;
        $this->address = (isset($data['address'])) ? $data['address'] : null;
        $this->created = (isset($data['created'])) ? $data['created'] : null;

        if (isset($data["password"])) {
            $this->setPassword($data["password"]);
        }
    }

    /**
     * get object data
     *
     * @return array
     */
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }
}

编辑module/Member/src/Member/Model/UserTable.php文件

UserTable类完成对users数据表的读取,写入等操作的封装。

public function fetchAll($paginated=false)
函数有个$paginated参数,设为true的时候,将进行分页显示操作,这里暂时设置为false,以后要用到。

<?php
/**
 * This source file is part of Qiai.
 *
 * PHP Version >=5.3
 *
 * @category   Qiai_Application
 * @package    Member
 * @subpackage Model
 * @author     Sai (QIAI) <sai@qiais.com>
 * @license    Qiai-License http://www.qiai.com/licenses/qiai.ck.html
 * @link       http://www.qiais.com
 */

namespace Member\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;

/**
 * Member: TableGateway
 *
 * @category   Gc_Application
 * @package    Member
 * @subpackage Model
 */
class UserTable
{
    /**
    * TableGateway
    */
    protected $tableGateway;

    /**
     * __construct
     *
     * @param TableGateway $tableGateway TableGateway
     *
     * @return void
     */
    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    /**
     * fetchAll: get all data from table member.
     *
     * @return ResultSet
     */
    public function fetchAll($paginated=false)
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    /**
     * saveMember: save data for user.
     *
     * @param Member $user user object
     *
     * @return ResultSet
     */
    public function saveUser(User $user)
    {
        $nowtime = date("Y-m-d H:i:s");
        $data = array(
            'email' => $user->email,
            'name'  => $user->name,
            'role'  => $user->role,
            'password'  => $user->password,
            'tel'  => $user->tel,
            'mobile'  => $user->mobile,
            'fax'  => $user->fax,
            'zipcode'  => $user->zipcode,
            'address'  => $user->address,
            'modified' => $nowtime
        );

        $id = (int)$user->id;
        if ($id == 0) {
            $data['created'] = $nowtime;
            $this->tableGateway->insert($data);
        } else {
            if ($this->getUser($id)) {
                if(empty($data['password']))
                    unset($data['password']);
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('User ID does not exist');
            }
        }
    }

    /**
     * Get User account by user id
     *
     * @param string $id string
     *
     * @throws \Exception
     * @return Row
     */
    public function getUser($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    /**
     * deleteMember: delete user.
     *
     * @param int $id user id
     *
     * @return void
     */
    public function deleteUser($id)
    {
        $this->tableGateway->delete(array('id' => $id));
    }

    /**
     * getUserByEmail: get user by email.
     *
     * @param string $email email address
     *
     * @return Object
     */
    public function getUserByEmail($email)
    {
        $rowset = $this->tableGateway->select(array('email' => $email));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $email");
        }
        return $row;
    }
}

编辑module/Member/src/Member/Module.php文件

<?php
/**
 * This source file is part of Qiai.
 *
 * PHP Version >=5.3
 *
 * @category   Qiai_Application
 * @package    Member
 * @subpackage Module
 * @author     Sai (QIAI) <sai@qiais.com>
 * @license    Qiai-License http://www.qiai.com/licenses/qiai.ck.html
 * @link       http://www.qiais.com
 */
namespace Member;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Member\Model\User;
use Member\Model\UserTable;

class Module implements AutoloaderProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    /**
     * get services
     *
     * @return array
     */
    public function getServiceConfig()
    {
        return array(
            'abstract_factories' => array(),
            'aliases' => array(),
            'factories' => array(
                // DB
                'UserTable' =>  function ($sm) {
                    $tableGateway = $sm->get('UserTableGateway');
                    $table = new UserTable($tableGateway);
                    return $table;
                },
                'UserTableGateway' => function ($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new User());
                    return new TableGateway('users', $dbAdapter, null, $resultSetPrototype);
                },
            ),
            'invokables' => array(),
            'services' => array(),
            'shared' => array(),
        );
    }
}

这里我们现在主要用到以下代码
‘factories’ => array(
// DB
‘UserTable’ => function ($sm) {
$tableGateway = $sm->get(‘UserTableGateway’);
$table = new UserTable($tableGateway);
return $table;
},
‘UserTableGateway’ => function ($sm) {
$dbAdapter = $sm->get(‘Zend\Db\Adapter\Adapter’);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway(‘users’, $dbAdapter, null, $resultSetPrototype);
},

通过zf2的ServiceManager连接数据库,获取容器,以便对users数据表操作。

编辑module/Member/src/Member/Controller/UserController.php文件

添加indexAction函数,读取所有用户

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Member\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Member\Model\User;
use Qiais\Auth;

class UserController extends AbstractActionController
{
    /**
     * index action
     *
     * @return array
     */
    public function indexAction()
    {
        // for no pagination
        $userTable = $this->getServiceLocator()->get('UserTable');
        $viewModel  = new ViewModel(array('users' => $userTable->fetchAll()));
        return $viewModel;
    }    
}

通过上面的代码,我们看到,zf2的ServiceManager让我们的代码变得非常简洁。读取所有用户数据只用了2行代码。

编辑module/Member/view/member/user/index.phtml文件

这是UserController的indexAction的默认视图view文件

<h3>Users</h3>
<table class="table table-bordered table-striped">
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Action</th>
</tr>
<?php
    foreach ($users as $user) :
?>
<tr>
    <td><?php echo $this->escapeHtml($user->name);?></td>
    <td><?php echo $this->escapeHtml($user->email);?></td>
    <td>
        <a href="<?php echo $this->url('member/user',
            array('action'=>'edit', 'id' => $user->id));?>">Edit</a> |
        <a href="<?php echo $this->url('member/user',
            array('action'=>'delete', 'id' => $user->id));?>" onclick="return confirm('Are you sure?')">Delete</a>
    </td>
</tr>
<?php endforeach; ?>
</table>
<hr />
<a class="btn btn-primary" href="<?php echo $this->url('member/user',array('action'=>'create'));?>">Add User</a>

访问http://zf2.tutorial/member/users/index

2014-03-05-01