下面创建一个链接数据库的开发实例

1、创建controller - IndexController.php

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace home\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use home\Model\Artical;
use home\Form\ArticalForm;
use Zend\Session\SessionManager as Zend_Session_SessionManager;

class  IndexController extends AbstractActionController{
   
    protected  $articalModel;

    public function getArticalModel()
    {
        if (!$this->articalModel) {
            $this->articalModel = $this-> getServiceLocator() ->get('home\Model\ArticalModel');
        }
        return $this->articalModel;
    }    
    
    public function indexAction(){
        $form = new ArticalForm();
        $form ->get('submit')->setAttribute('value', '提交');
        $request = $this->getRequest();
        if($request -> isPost()){
            $artical = new Artical();
            $form ->setInputFilter($artical -> getInputFilter());
            $form ->setData($request->getPost());
            if($form ->isValid()){
                $artical -> exchangeArray($form -> getData());
                $this->getArticalModel()->saveArtical($artical);
                return $this->redirect()->toRoute();
            }
        }
        $where = array();
        $order = array();
        $count =$this-> getArticalModel() -> getCount();
        $pagesize = 10;
        $nowpagenum = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1 ;
        $page = $this->PageNum($count, $pagesize ,$nowpagenum);
        $limit = array('limit' => ($nowpagenum-1)*$pagesize.','.$pagesize);
        $list = $this->getArticalModel() ->fetchAll($where,$order,$limit);
        return array(
            'form' => $form,
            'list' => $list,
            'page' => $page,
        );
    }
    
}
2、创建FORM表单相关内容 -ArticalForm.php

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

namespace home\Form;

use Zend\Form\Form;

class ArticalForm extends Form{
    
    public function __construct($name=null){
        
        parent::__construct('artical');
        
        $this->setAttribute('method', 'post');
        
        $this->add(array(
            'name' => 'id',
            'attributes' => array(
                'type' => 'hidden',
            ),
        ));
        
        $this->add(array(
            'name' => 'title',
            'attributes' => array(
                'type' => 'text',
            ),
            'options' => array(
                'label' => '标题',
            ),
        ));
        
        $this->add(array(
            'name' => 'content',
            'attributes' => array(
                'type'  => 'text',
            ),
            'options' => array(
                'label' => '内容',
            ),
        ));
        
        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type'  => 'submit',
                'value' => '提交',
                'id' => 'submitbutton',
            ),
        ));
        
    }
    
}

?>

3、创建Model-Artical.php以及数据库操作Model-ArticalModel.php

Artical.php代码如下:

<?php
namespace home\Model;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Artical implements InputFilterAwareInterface{
    
    public $id;
    public $titile;
    public $content;
    
    protected $inputFilter;
    
    public function exchangeArray($data){
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->title = (isset($data['title'])) ? $data['title'] : null;
        $this->content = (isset($data['content'])) ? $data['content'] : null;
    }
    
    public function getArrayCopy(){
        return get_object_vars($this);
    }
    
    public function setInputFilter(InputFilterInterface $inputFilter){
        throw new Exception('Not Used!');
    }
    
    public function getInputFilter(){
        if(!$this->inputFilter){
            $inputFilter = new InputFilter();
            $factory =new InputFactory();
            $inputFilter ->add($factory ->createInput(array(
                'name' => 'id',
                'required' => true,
                'filters' => array(
                    array('name' => 'Int'),
                )
            )));
            $inputFilter ->add($factory ->createInput(array(
                'name' => 'title',
                'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name' => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min' => 1,
                            'max' => 100,
                        ),
                    ),
                ),
            )));
            $inputFilter ->add($factory ->createInput(array(
                'name' => 'content',
                'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name' => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min' => 1,
                        ),
                    ),
                ),
            )));
            $this->inputFilter = $inputFilter;
        }
        return $this->inputFilter;
    }
    
}

?>

ArticalModel.php代码如下:

<?php

namespace home\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;

class ArticalModel extends AbstractTableGateway{
    
    protected $table = 'artical';
    
    public function __construct(Adapter $adapter){
        $this -> adapter = $adapter;
        $this -> resultSetPrototype = new ResultSet();
        $this -> resultSetPrototype -> setArrayObjectPrototype(new Artical());
        $this -> initialize();
    }
    
    public function fetchAll($where,$order,$limit){
        $resultSet = $this -> dbSelect($where,$order,$limit);
        return $resultSet;
    }
    
    public function getCount(){
        $result =  $this->dbCount();
        return $result[0];
    }
    
    public function getArtical($id){
        $id = (int) $id;
        $rowSet = $this -> select(array('id'=>$id));
        $rows = $rowSet -> current();
        if(!$rows){
            throw new Exception("Could not find row {$id}");
        }
        return $rows;
    }
    
    public function saveArtical(Artical $artical){
        $data = array(
            'title' => $artical -> title,
            'content' => $artical -> content
        );
        $id = (int) $artical -> id;
        if($id == 0){
            $this->insert($data);
        }else{
            if($this->getArtical($id)){
                $this->update($data,array('id'=>$id));
            }else{
                throw new Exception('Form Id is not find!');
            }
        }
    }
    
    public function deleteArtical($id){
        $this->delete(array('id'=>$id));
    }
    
    public function count(){
        
    }
    
}

?>

4、view部分

zf生成表单部分:

<?php
    $form = $this -> form ;
    $form ->setAttribute('action', $this -> url('home',array('action' => 'index')));
    $form ->prepare();
    echo $this->form()->openTag($form);
    echo $this->formHidden($form->get('id'));
    echo $this->formRow($form->get('title'));
    echo $this->formRow($form->get('content'));
    echo $this->formInput($form->get('submit'));
    echo $this->form()->closeTag($form);
?>

页面显示部分:

<?php
    echo '<table>'; 
    echo '<tr><th>序号</th><th>标题</th><th>内容</th></tr>';
    for($i=0;$i<count($this->list);$i++){
        echo '<tr><td>'.$this->list[$i][0].'</td><td>'.$this->list[$i][1].'</td><td>'.$this->list[$i][2].'</td></tr>';
    }
    echo  '</table>';
    echo $this->page;
?>

5、模块根目录下Module.php配置部分:

<?php
/**
 * @todo 配置该模块中使用到得数据库模型
 * @return String $table
 */

namespace home;

use home\Model\ArticalModel;

class Module
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
    
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'home\Model\ArticalModel' =>  function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table = new ArticalModel($dbAdapter);
                    return $table;
                },
            ),
        );
    }    

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

由此就完成了一个链接数据库的发布文章的ZF开发实例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值