PHPEye开源社区 » Zend Framework 使用讨论 » 初学者的ZFRC2测试DEMO
《Programming PHP》第二版上市
2007-6-12 13:32 mmocom
初学者的ZFRC2测试DEMO

:handshake :) ~~~由于工作原因 近段时间无法持续更新~~请大家见谅~~ :( :(
index.php引导文件

[php]error_reporting(E_ALL|E_STRICT);

date_default_timezone_set('Asia/Shanghai');

//目录分隔符号
$ds = DIRECTORY_SEPARATOR;
//路径分隔符号
$ps = PATH_SEPARATOR;
$ABS_ROOT_PATH = realpath(dirname(__FILE__));
$REL_ROOT_PATH =  substr($_SERVER['PHP_SELF'], 0 , strpos($_SERVER['PHP_SELF'],'/index.php'));

set_include_path('.'.PATH_SEPARATOR.'./library'
        .PATH_SEPARATOR.'./application/models/'
        .PATH_SEPARATOR.get_include_path());

require('Zend/Loader.php');

//自动加载类
function __autoload($class){
        Zend_Loader::loadClass($class);
}

//数据库配置
$dbParams = new Zend_Config_Ini('./config/database.ini','CMSDB');
$db = Zend_Db::factory($dbParams->adapter,$dbParams->toArray());
$db->query("set names {$dbParams->charset};");
Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set('db',$db);


//SMARTY配置
$smartyParams = new Zend_Config_Ini('./config/smarty.ini', 'Smarty');
$smarty = new Custom_View_Smarty($smartyParams->toArray());
Zend_Registry::set('smarty',$smarty);


//初始控制器
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory(array(
      'default' => './application/modules/default/controllers',
      'admin'    => './application/modules/admin/controllers'
));
$frontController->addModuleDirectory('./application/modules');
$frontController->setParam('noViewRenderer',true);
$frontController->setBaseUrl($REL_ROOT_PATH);

try{
        $frontController->dispatch();
}catch(Zend_Controller_Dispatcher_Exception $e){
        $frontController->getResponse()->setHttpResponseCode(404);
        $frontController->getResponse()->__toString();
}[/php]
database.ini
[code][CMSDB]
adapter=pdo_mysql
host=localhost
username=root
password=
dbname=cms
charset=gbk[/code]
smarty.ini
[code][Smarty]
left_delimiter                =        "{"
right_delimiter                =        "}"
template_dir                =        "./www/templates"
compile_dir                =        "./www/templates_c"
[/code]
application\modules\default\controllers\IndexController.php
[php]class IndexController extends Zend_Controller_Action
{
        public function init()
        {
                $this->db = Zend_Registry::get('db');
                $this->smarty = Zend_Registry::get('smarty');
        }
       
        public function indexAction()
        {
                echo 'Hello from IndexController';
                $this->smarty->display('index.html');
        }
       
       
        public function __call($method, $args)   
        {        
                if ('Action' == substr($method, -6))
                {            
                        // If the action method was not found, forward to the index action
                        //如果action方法没有找到,则转向到index action           
                        return $this->_forward('index');        
                }        
                // all other methods throw an exception
                //所有其他的方法则扔出一个错误信息  
                throw new Exception('Invalid method "' . $method . '" called');   
        }
       
        public function noRouterAction()
        {
                $this->_redirect('/');
        }
}[/php]
application\modules\admin\controllers\IndexController.php

[php]class Admin_IndexController extends Zend_Controller_Action
{
        public function init()
        {}
       
        public function indexAction()
        {
                echo 'Hello from Admin_IndexController-indexAction';
        }
}[/php]

/********************************************************************************************************
感谢ZF MSN群里的 Haohappy,beyond_dream,萧林,Ken,周超,黔驴,phpwb
和phpeye论坛里的wanghaozi,linren119 等等
~~~给我的热心帮助~~谢谢大家~~^*^
版本:ZFRC2
更新日期:2007年6月26日
********************************************************************************************************/
[color=Red]DEMO主要功能~~都是一些常用的 必须的功能哈~~希望大家能用到

简单的数组显示/smarty---SmartyController.php

简单的数据操作/sql-----SqlController.php

综合:验证用户是否可以访问+采用Smarty的视图 + 数据表单(添加、修改、删除)+翻页的操作/form----FormController.php

用户认证操作/auth----AuthController.php

SESSION的一些简单操作/session----SessionController.php[/color]

:hug: 附件下载:更新于20070626~~~:victory: [color=Red]附件下载[/color]:handshake 版本原因 暂停下载 敬请谅解

版本日志:
0623:这次版本改动很小~~修改了smarty view 添加了auth~~如果有错误请更帖~~我会尽快修正~~谢谢:handshake
0626:这次版本添加了一个翻页功能,还添加了一些SESSION的简单操作

[[i] 本帖最后由 mmocom 于 2008-1-2 17:21 编辑 [/i]]

2007-6-13 23:14 smallcat
写的不错,最近刚好打算学习一下ZF。正好当作参考。谢谢

2007-6-14 22:16 beyond_dream
UP

明天到公司去测试下

2007-6-17 00:13 gbbnvc
写的不错:)

2007-6-20 18:13 wanghaozi
提个建议

[code]
$dbparam = array ('host' => $config->database->host,
        'username'        =>        $config->database->username,
        'password'        =>        $config->database->password,
        'dbname'        =>        $config->database->dbname);
        
$db = Zend_Db::factory($config->database->type,$dbparam);
[/code]

这段可以用下面的来代替
[code]
$db = Zend_Db::factory($config->database->type,$config->database->toArray());
[/code]

目前最新版本的zf 里面  Zend_Config_Ini 的 把原来地asArray()方法给去除了 统一用toArray() ,个人觉得zf开始从细节上进行修改了

2007-6-20 23:50 mmocom
[quote]原帖由 [i]wanghaozi[/i] 于 2007-6-20 18:13 发表 [url=http://www.phpeye.com/bbs/redirect.php?goto=findpost&pid=277&ptid=53][img]http://www.phpeye.com/bbs/images/common/back.gif[/img][/url]

$dbparam = array ('host' => $config->database->host,
        'username'        =>        $config->database->username,
        'password'        =>        $config->database->password,
        'dbname' ... [/quote]


谢谢~~我将在以后的版本进行改进~~~:) :) :handshake

2007-6-21 17:10 linren119
section模块无法显示是由于数组下标不规范引起的,有3种方法解决:
1、把数组下标去掉,默认0,1,2,3。。。即可
2、规范数组下标,参考section的start和step参数
3、改成这样的方式:
数组:$val2[] = array(9 => 'Tennis', 3 => 'Swimming', 8 => 'Coding');
模板:
{section name=customer2 loop=$disval2}
     <li>id: {$disval2[customer2].9}</li>
<li>id: {$disval2[customer2].3}</li>
<li>id: {$disval2[customer2].8}</li>
{/section}

2007-6-23 01:04 mmocom
[quote]原帖由 [i]linren119[/i] 于 2007-6-21 17:10 发表 [url=http://www.phpeye.com/bbs/redirect.php?goto=findpost&pid=289&ptid=53][img]http://www.phpeye.com/bbs/images/common/back.gif[/img][/url]
section模块无法显示是由于数组下标不规范引起的,有3种方法解决:
1、把数组下标去掉,默认0,1,2,3。。。即可
2、规范数组下标,参考section的start和step参数
3、改成这样的方式:
数组:$val2[] = array(9 => 'Tennis', 3 => 'Sw ... [/quote]


谢谢哈~~我会在以后的版本里~·:hug:  改正

2007-6-26 17:55 chenjiafeng
:L 这也是写给初学者看的?

2007-6-26 21:06 mmocom
[quote]原帖由 [i]chenjiafeng[/i] 于 2007-6-26 17:55 发表 [url=http://www.phpeye.com/bbs/redirect.php?goto=findpost&pid=328&ptid=53][img]http://www.phpeye.com/bbs/images/common/back.gif[/img][/url]
:L 这也是写给初学者看的? [/quote]


确实很多都封装成类~~看起来可能会有点难度~~不过其实很简单的哈~~不懂多问下哦~~:victory: :victory:

2007-6-27 13:11 chenjiafeng
Fatal error: Uncaught exception 'Zend_Config_Exception' with message 'Section 'zf' cannot be found in ./config/config.xml' in E:\AppServ\www\zf\library\Zend\Config\Xml.php:80 Stack trace: #0 E:\AppServ\www\zf\index.php(39): Zend_Config_Xml->__construct('./config/config...', 'zf') #1 {main} thrown in E:\AppServ\www\zf\library\Zend\Config\Xml.php on line 80
怎么我安装上出现这样的错误,是不是少文件啊?

2007-6-27 15:12 mmocom
[quote]原帖由 [i]chenjiafeng[/i] 于 2007-6-27 13:11 发表 [url=http://www.phpeye.com/bbs/redirect.php?goto=findpost&pid=335&ptid=53][img]http://www.phpeye.com/bbs/images/common/back.gif[/img][/url]
Fatal error: Uncaught exception 'Zend_Config_Exception' with message 'Section 'zf' cannot be found in ./config/config.xml' in E:\AppServ\www\zf\library\Zend\Config\Xml.php:80 Stack trace: #0 E:\AppSer ... [/quote]


你修改的$dbconfig = new Zend_Config_Xml('./config/config.xml','mmocom');为$dbconfig = new Zend_Config_Xml('./config/config.xml','zf');

这个里面的mmocom是XML文件里的section~不是目录名
记得要开启PHP里的PHP_PDO

2007-6-27 17:04 chenjiafeng
好的,谢谢

2007-7-3 10:38 linren119
提供一份数据库

2007-7-3 10:52 linren119
FormController.php的

$this->user = new Name();

这行的Name类是在那个文件里的?

2007-7-3 11:14 linren119
找到了。。。。

2007-7-17 10:11 123waily
mmocom ,提供一份数据库,
Fatal error: Uncaught exception 'Zend_Db_Adapter_Exception' with message 'SQLSTATE[42000] [1049] Unknown database 'mmocom'' in E:\AppServ\www\mmocom\library\Zend\Db\Adapter\Pdo\Abstract.php:131 Stack trace: #0 E:\AppServ\www\mmocom\library\Zend\Db\Adapter\Abstract.php(246): Zend_Db_Adapter_Pdo_Abstract->_connect() #1 E:\AppServ\www\mmocom\library\Zend\Db\Adapter\Pdo\Abstract.php(206): Zend_Db_Adapter_Abstract->query('set names gbk;', Array) #2 E:\AppServ\www\mmocom\index.php(42): Zend_Db_Adapter_Pdo_Abstract->query('set names gbk;') #3 {main} thrown in E:\AppServ\www\mmocom\library\Zend\Db\Adapter\Pdo\Abstract.php on line 131

2007-7-19 14:40 mmocom
Page(翻页类)用于Zend Framwork

[code]<?php
// Page(翻页类)用于Zend Framwork
class Custom_Page_ZF
{
        var $path;                                          //路径
        var $totalnum;                //记录总数
        var $perpagenum;              //每一页显示的记录数
        var $totalpage;               //总页数
        var $curpage;                 //当前页码
        var $offsetnum;               //记录偏移量
        var $linkpage;                //url连接
        var $offsetpage = 5;          //页码偏移量,这里可随意更改
        var $disnum;                                  //显示可选择的页面数
        var $pagetype;                                  //显示样式
                  
        public function __construct($param)
        {
                $this->path = $param['path'];
                $this->totalnum = $param['totalnum'];
                $this->perpagenum = $param['perpagenum'];
                $this->curpage = isset( $param['curpage'] ) ? intval( $param['curpage'] ) : '1';
                $this->totalpage = ceil( $this->totalnum / $this->perpagenum );
                $this->offsetnum = $this->perpagenum * ( $this->curpage - 1 );               
                $this->disnum = $param['disnum'];//当调用getNumPage()时需要此参数       
        }

       
        function getCharPage()
        {
                if ( $this->totalnum > $this->perpagenum )//当总记录数大于每页记录数时
                {
                        if ( $this->curpage == 1 && $this->totalpage > 1 )//当前页为第1页并且总页数大于1
                        {
                       
                                $this->linkpage = "<a>首页</a>|<a>上一页</a>|<a href=".$this->path."/page/".( $this->curpage + 1 )." >下一页</a>|<a href=".$this->path."/page/".$this->totalpage." >尾页</a>";
                       
                        } elseif ( $this->curpage > 1 && $this->curpage < $this->totalpage ){//当前页大于1并且当前页小于总页数
                       
                                $this->linkpage = "<a href=".$this->path."/page/1 >首页<a>|"
                                                                . "<a href=".$this->path."/page/".($this->curpage-1)." >上一页</a>|"
                                                                . "<a href=".$this->path."/page/".($this->curpage+1)." >下一页</a>|"
                                                                . "<a href=".$this->path."/page/".$this->totalpage." >尾 页</a>";
                       
                        } elseif ( $this->curpage == $this->totalpage && $this->totalpage > 1 ){
                       
                                $this->linkpage = "<a href=".$this->path."/page/1 >首 页<a>|"
                                                                . "<a href=".$this->path."/page/".($this->curpage-1)." >上一页</a>|<a>下一页</a>|<a>尾页</a>";
                        }
                }
                return "<div id=\"pager\">".$this->linkpage."</div>";
        }
       
        function getNumPage()
        {
                //总记录数大于每页记录数
                if( $this->totalnum > $this->perpagenum )
                {
                        //要求显示的数字组页数大于总页数
                        if ( $this->disnum >= $this->totalpage )
                        {
                                $from = 1;
                                $to = $this->totalpage;
                        } else {
                                $from = $this->curpage - $this->offsetpage;
                                $to = $from + $this->disnum - 1;
                                if( $from < 1 ){
                                        $to = $this->curpage + 1 - $from;
                                        $from = 1;
                                        if ( $to - $from < $this->disnum ){
                                                $to = $this->disnum;
                                        }
                                } elseif ( $to > $this->totalpage ){
                                        $from = $this->totalpage - $disnum + 1;
                                        $to = $this->totalpage;
                                }
                               
                        }
                        $url = '';
                        for ( $i = $from; $i <= $to; $i++)
                        {
                                if( $this->curpage == $i )
                                {
                                        $url .= "<a>".$i."</a>";
                                }else{
                                        $url .= "<a href=".$this->path."/page/".$i." >".$i."</a>";
                                }
                        }
                       

                        $urlstart = "<a href=".$this->path."/page/1 >首页</a>"
                        . "<a href=".$this->path."/page/".( $this->curpage - 1 )." >上一页</a>";
                        $urlend = "<a href=".$this->path."/page/".( $this->curpage + 1 )." >下一页</a>";

                        //当前页为第1页并且总页数大于1
                        if( $this->curpage == 1 && $this->totalpage > 1 )
                        {
                                $this->linkpage = $url.$urlend;
                        }
                        elseif ( $this->curpage > 1 && $this->curpage < $this->totalpage )//当前页大于1并且当前页小于总页数
                        {
                                $this->linkpage = $urlstart.$url.$urlend;
                        }
                        elseif ( $this->curpage == $this->totalpage && $this->totalpage > 1 )
                        {
                                $this->linkpage = $urlstart.$url;
                        }

                       
                }else{
                        $this->linkpage = "1";
                }
                return "<div id=\"pager\">".$this->linkpage."</div>";
        }
       
        //获取总页数
        function getTotalPage()
        {
                return $this->totalpage;
        }
       
}
?>[/code]

2007-7-19 14:40 mmocom
Zend Framework 1.0与 PHP模板引擎SMARTY 的配置

[code]<?php
/**
*
* Zend Framework 与 PHP模板引擎SMARTY 的配置
*
*
*/
require_once 'Smarty/Smarty.class.php';

class Custom_View_Smarty implements Zend_View_Interface
{
        /**
         * Smarty object     
         * @var Smarty     
         */   
        protected $_smarty;
       
        /**
         * Constructor
         *
         * @param string $tmplPath
         * @param array $extraParams
         * @return void
         */   
        public function __construct(array $smartyParams = array())
        {
                //检测SMARTY配置参数是否合格
                $this->_checkRequiredOptions($smartyParams);
               
                $this->_smarty = new Smarty;

            foreach ((array) $smartyParams as $key => $value)
                {
                    $this->_smarty->$key = $value;
            }
        }
        /**     
         * Return the template engine object     
         * 返回模板引擎对象   
         * @return Smarty     
         */   
        public function getEngine()   
        {      
                 return $this->_smarty;   
        }
       
       
        public function setScriptPath($path)   
        {      
        }
       

    public function getScriptPaths()
        {
        }

    /**
     * Set a base path to all view resources
     *
     * @param  string $path
     * @param  string $classPrefix
     * @return void
     */
    public function setBasePath($path, $classPrefix = 'Zend_View')
        {
        }

    /**
     * Add an additional path to view resources
     *
     * @param  string $path
     * @param  string $classPrefix
     * @return void
     */
    public function addBasePath($path, $classPrefix = 'Zend_View')
        {
        }
        /**     
         * 设置模板路径     
         *     
         * @param string $path The directory to set as the path.     
         * @return void     
         */
        public function setTemplatePath()
        {
                if (is_readable( $this->_smarty->template_dir ))
                {            
                        return $this->_smarty->template_dir;
                }
                throw new Exception('Invalid TemplatePath provided');
        }  
        /**     
         * 设置模板编译路径     
         *     
         * @param string $path The directory to set as the path.     
         * @return void     
         */
        public function setCompilePath()
        {
                if (is_readable( $this->_smarty->compile_dir))
                {            
                        return $this->_smarty->compile_dir;
                }
                throw new Exception('Invalid CompilePath provided');
        }
       
        public function getTemplatePath()
    {
        return $this->_smarty->template_dir;
    }   
       
        /**     
         * 分配变量给模板 Assign a variable to the template     
         *     
         * @param string $key The variable name.     
         * @param mixed $val The variable value.     
         * @return void     
         */   
        public function __set($key, $val)   
        {        
                $this->_smarty->assign($key, $val);   
        }   
        /**     
         * Retrieve an assigned variable     
         *     
         * @param string $key The variable name.     
         * @return mixed The variable value.     
         */   
        public function __get($key)   
        {        
                return $this->_smarty->get_template_vars($key);   
        }   
        /**     
         * Allows testing with empty() and isset() to work     
         *     
         * @param string $key     
         * @return boolean     
         */                   
        public function __isset($key)   
        {        
                return (null !== $this->_smarty->get_template_vars($key));   
        }   
        /**     
         * Allows unset() on object properties to work     
         *     
         * @param string $key   
         * @return void     
         */   
        public function __unset($key)   
        {        
                $this->_smarty->clear_assign($key);   
        }   
        /**     
         * 分配变量给模板 Assign variables to the template   
         *     
         * Allows setting a specific key to the specified value, OR passing an array     
         * of key => value pairs to set en masse.     
         *     
         * @see __set()     
         * @param string|array $spec The assignment strategy to use (key or array of key   
         * => value pairs)     
         * @param mixed $value (Optional) If assigning a named variable, use this     
         * as the value.     
         * @return void     
         */   
        public function assign($spec, $value = null)   
        {        
                if (is_array($spec))
                {            
                        $this->_smarty->assign($spec);            
                        return;        
                }        
                $this->_smarty->assign($spec, $value);   
        }   
        /**     
         * 清楚所有已经分配变量 Clear all assigned variables     
         *     
         * Clears all variables assigned to Zend_View either via {@link assign()} or     
         * property overloading ({@link __get()}/{@link __set()}).     
         *     
         * @return void     
         */   
        public function clearVars()   
        {        
                $this->_smarty->clear_all_assign();   
        }   
        /**     
         * 处理模板并返回输出的内容 Processes a template and returns the output.     
         *     
         * @param string $name The template to process.     
         * @return string The output.     
         */   
        public function render($name)   
        {        
                return $this->_smarty->fetch($name);   
        }
       
        /**     
         * 处理模板并显示输出内容 Processes a template and display the output.     
         *     
         * @param string $name The template to process.     
         * @return string The output.     
         */        
        public function display($name)   
        {        
                return $this->_smarty->display($name);   
        }
       
       
         /**
     * Check for extraParams options that are mandatory.
         * 检测 extraParams 的参数项
     * Throw exceptions if any are missing.
     * 抛出错误异常
     * @param array $extraParams
     * @throws Zend_View_Exception
     */
    protected function _checkRequiredOptions(array $extraParams)
    {
        // we need at least a template_dir and compile_dir
        if (! array_key_exists('template_dir', $extraParams)) {
            require_once 'Zend/View/Exception.php';
            throw new Zend_View_Exception("Configuration array must have a key for 'template_dir' for Smarty View.",$this);
        }

        if (! array_key_exists('compile_dir', $extraParams)) {
            /**
             * @see Zend_View_Exception
             */
            require_once 'Zend/View/Exception.php';
            throw new Zend_View_Exception("Configuration array must have a key for 'compile_dir' for Smarty Compile.",$this);
        }

    }
       
}

?>[/code]

2007-8-3 18:02 zhuzhiwu
写的相当的好啊,一看就是高手,就是不知道杂用,可否简单说说

页: [1] 2
查看完整版本: 初学者的ZFRC2测试DEMO


Powered by Discuz! Archiver 5.5.0  © 2001-2006 Comsenz Inc.