PHPEye开源社区 » Zend Framework 使用讨论 » Zend Framework 1.5版本DEMO
《Programming PHP》第二版上市
2008-5-13 13:26 mmocom
Zend Framework 1.5版本DEMO

学习DEMO!

目录结构
[attach]62[/attach]

.htaccess
[code]RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php[/code]

引导文件
index.php


第三方类库
模板引擎:smarty
编辑器:sinaEditor,FckEditor
文件上传:
图片处理:
翻页程序:



持续更新中。。。

Powered By [url=http://www.mmocom.cn]MMOCom.CN[/url]
[url=http://blog.163.com/huv520@126]BLOG[/url]
联系方式QQ:184285285

[[i] 本帖最后由 mmocom 于 2008-5-13 14:15 编辑 [/i]]

2008-5-13 13:34 mmocom
引导文件index.php

[php]
<?php

define('ROOT_DIR', dirname(__FILE__));
define('BASE_DIR', dirname(__FILE__));

// Setup path to the Zend Framework files
set_include_path('.'
. PATH_SEPARATOR . ROOT_DIR.'/library/'
. PATH_SEPARATOR . BASE_DIR.'/application/models'
. PATH_SEPARATOR . get_include_path()
);

// Register the autoloader
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

Zend_Session::start();

//Initialise MySQL
$dbParams = new Zend_Config_Ini(ROOT_DIR.'/config/config.ini','SysDB');
$db = Zend_Db::factory($dbParams->adapter,$dbParams->toArray());
$db->query("set names {$dbParams->charset};");
Zend_Db_Table::setDefaultAdapter($db);
Zend_Registry::set('sysdb',$db);

//Initialise SMARTY
$smartyParams = new Zend_Config_Ini(ROOT_DIR.'/config/config.ini', 'SysTpl');
$smarty = new ORG_View_Smarty($smartyParams->toArray());
Zend_Registry::set('systpl',$smarty);


// Run!
$frontController = Zend_Controller_Front::getInstance();
$frontController->addControllerDirectory(BASE_DIR.'/application/controllers');
$frontController->setParam('noViewRenderer',true);

$frontController->throwExceptions(true);
try {
    $frontController->dispatch();
} catch(Exception $e) {
    echo nl2br($e->__toString());
}

[/php]

2008-5-13 13:42 mmocom
config.ini配置文件

[code]
[SysDB]
adapter                 =         pdo_mysql
host                 =         localhost
username         =         root
password         =        root
dbname                 =         test
charset                 =         utf8
prefix           =

[SysTpl]
left_delimiter                =        "{"
right_delimiter                =        "}"
template_dir                =        "tpl/templates"
compile_dir                =        "tpl/templates_c"
[/code]

2008-5-13 13:44 mmocom
ORG_Editor类库

ORG_Editor_Sina
[php]
<?php
/**
* Title:新浪博客编辑器PHP版封装类
* coder:gently
* Date:2007年11月9日
* Power by ZendStudio.Net
* [url]http://www.zendstudio.net/[/url]
* 您可以任意使用和传播,但请保留本段信息!
*
*/
class ORG_Editor_Sina{
        var $BasePath;
        var $Width;
        var $Height;
        var $eName;
        var $Value;
        var $AutoSave;
        function ORG_Editor_Sina($eName){
                $this->eName=$eName;
                $this->BasePath='.';
                $this->AutoSave=false;
                $this->Height=460;
                $this->Width=630;
        }
        function __construct($eName){
                $this->ORG_Editor_Sina($eName);
        }
        function Create(){
                $ReadCookie=$this->AutoSave?1:0;
                print <<<eot
                <textarea name="{$this->eName}" id="{$this->eName}" style="display:none;">{$this->Value}</textarea>
                <iframe src="{$this->BasePath}/Edit/editor.htm?id={$this->eName}&ReadCookie={$ReadCookie}" frameBorder="0" marginHeight="0" marginWidth="0" scrolling="No" width="{$this->Width}" height="{$this->Height}"></iframe>
eot;
        }
}
[/php]

ORG_Editor_FCK

[php]<?php
/*
* FCKeditor - The text editor for Internet - [url]http://www.fckeditor.net[/url]
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
*  - GNU General Public License Version 2 or later (the "GPL")
*    [url]http://www.gnu.org/licenses/gpl.html[/url]
*
*  - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
*    [url]http://www.gnu.org/licenses/lgpl.html[/url]
*
*  - Mozilla Public License Version 1.1 or later (the "MPL")
*    [url]http://www.mozilla.org/MPL/MPL-1.1.html[/url]
*
* == END LICENSE ==
*
* This is the integration file for PHP 5.
*
* It defines the FCKeditor class that can be used to create editor
* instances in PHP pages on server side.
*/

class ORG_Editor_FCK
{
        /**
         * Name of the FCKeditor instance.
         *
         * @access protected
         * @var string
         */
        public $InstanceName ;
        /**
         * Path to FCKeditor relative to the document root.
         *
         * @var string
         */
        public $BasePath ;
        /**
         * Width of the FCKeditor.
         * Examples: 100%, 600
         *
         * @var mixed
         */
        public $Width ;
        /**
         * Height of the FCKeditor.
         * Examples: 400, 50%
         *
         * @var mixed
         */
        public $Height ;
        /**
         * Name of the toolbar to load.
         *
         * @var string
         */
        public $ToolbarSet ;
        /**
         * Initial value.
         *
         * @var string
         */
        public $Value ;
        /**
         * This is where additional configuration can be passed.
         * Example:
         * $oFCKeditor->Config['EnterMode'] = 'br';
         *
         * @var array
         */
        public $Config ;

        /**
         * Main Constructor.
         * Refer to the _samples/php directory for examples.
         *
         * @param string $instanceName
         */
        public function __construct( $instanceName )
        {
                $this->InstanceName        = $instanceName ;
                $this->BasePath                = '/fckeditor/' ;
                $this->Width                = '100%' ;
                $this->Height                = '200' ;
                $this->ToolbarSet        = 'Default' ;
                $this->Value                = '' ;

                $this->Config                = array() ;
        }

        /**
         * Display FCKeditor.
         *
         */
        public function Create()
        {
                echo $this->CreateHtml() ;
        }

        /**
         * Return the HTML code required to run FCKeditor.
         *
         * @return string
         */
        public function CreateHtml()
        {
                $HtmlValue = htmlspecialchars( $this->Value ) ;

                $Html = '' ;

                if ( $this->IsCompatible() )
                {
                        if ( isset( $_GET['fcksource'] ) && $_GET['fcksource'] == "true" )
                                $File = 'fckeditor.original.html' ;
                        else
                                $File = 'fckeditor.html' ;

                        $Link = "{$this->BasePath}editor/{$File}?InstanceName={$this->InstanceName}" ;

                        if ( $this->ToolbarSet != '' )
                                $Link .= "&Toolbar={$this->ToolbarSet}" ;

                        // Render the linked hidden field.
                        $Html .= "<input type=\"hidden\" id=\"{$this->InstanceName}\" name=\"{$this->InstanceName}\" value=\"{$HtmlValue}\" style=\"display:none\" />" ;

                        // Render the configurations hidden field.
                        $Html .= "<input type=\"hidden\" id=\"{$this->InstanceName}___Config\" value=\"" . $this->GetConfigFieldString() . "\" style=\"display:none\" />" ;

                        // Render the editor IFRAME.
                        $Html .= "<iframe id=\"{$this->InstanceName}___Frame\" src=\"{$Link}\" width=\"{$this->Width}\" height=\"{$this->Height}\" frameborder=\"0\" scrolling=\"no\"></iframe>" ;
                }
                else
                {
                        if ( strpos( $this->Width, '%' ) === false )
                                $WidthCSS = $this->Width . 'px' ;
                        else
                                $WidthCSS = $this->Width ;

                        if ( strpos( $this->Height, '%' ) === false )
                                $HeightCSS = $this->Height . 'px' ;
                        else
                                $HeightCSS = $this->Height ;

                        $Html .= "<textarea name=\"{$this->InstanceName}\" rows=\"4\" cols=\"40\" style=\"width: {$WidthCSS}; height: {$HeightCSS}\">{$HtmlValue}</textarea>" ;
                }

                return $Html ;
        }

        /**
         * Returns true if browser is compatible with FCKeditor.
         *
         * @return boolean
         */
        public function IsCompatible()
        {
                return FCKeditor_IsCompatibleBrowser() ;
        }

        /**
         * Get settings from Config array as a single string.
         *
         * @access protected
         * @return string
         */
        public function GetConfigFieldString()
        {
                $sParams = '' ;
                $bFirst = true ;

                foreach ( $this->Config as $sKey => $sValue )
                {
                        if ( $bFirst == false )
                                $sParams .= '&' ;
                        else
                                $bFirst = false ;

                        if ( $sValue === true )
                                $sParams .= $this->EncodeConfig( $sKey ) . '=true' ;
                        else if ( $sValue === false )
                                $sParams .= $this->EncodeConfig( $sKey ) . '=false' ;
                        else
                                $sParams .= $this->EncodeConfig( $sKey ) . '=' . $this->EncodeConfig( $sValue ) ;
                }

                return $sParams ;
        }

        /**
         * Encode characters that may break the configuration string
         * generated by GetConfigFieldString().
         *
         * @access protected
         * @param string $valueToEncode
         * @return string
         */
        public function EncodeConfig( $valueToEncode )
        {
                $chars = array(
                        '&' => '%26',
                        '=' => '%3D',
                        '"' => '%22' ) ;

                return strtr( $valueToEncode,  $chars ) ;
        }
}



/**
* Check if browser is compatible with FCKeditor.
* Return true if is compatible.
*
* @return boolean
*/
function FCKeditor_IsCompatibleBrowser()
{
        if ( isset( $_SERVER ) ) {
                $sAgent = $_SERVER['HTTP_USER_AGENT'] ;
        }
        else {
                global $HTTP_SERVER_VARS ;
                if ( isset( $HTTP_SERVER_VARS ) ) {
                        $sAgent = $HTTP_SERVER_VARS['HTTP_USER_AGENT'] ;
                }
                else {
                        global $HTTP_USER_AGENT ;
                        $sAgent = $HTTP_USER_AGENT ;
                }
        }

        if ( strpos($sAgent, 'MSIE') !== false && strpos($sAgent, 'mac') === false && strpos($sAgent, 'Opera') === false )
        {
                $iVersion = (float)substr($sAgent, strpos($sAgent, 'MSIE') + 5, 3) ;
                return ($iVersion >= 5.5) ;
        }
        else if ( strpos($sAgent, 'Gecko/') !== false )
        {
                $iVersion = (int)substr($sAgent, strpos($sAgent, 'Gecko/') + 6, 8) ;
                return ($iVersion >= 20030210) ;
        }
        else if ( strpos($sAgent, 'Opera/') !== false )
        {
                $fVersion = (float)substr($sAgent, strpos($sAgent, 'Opera/') + 6, 4) ;
                return ($fVersion >= 9.5) ;
        }
        else if ( preg_match( "|AppleWebKit/(\d+)|i", $sAgent, $matches ) )
        {
                $iVersion = $matches[1] ;
                return ( $matches[1] >= 522 ) ;
        }
        else
                return false ;
}[/php]



Simple Usage:

/vendor/.htaccess
[code]RewriteEngine off[/code]

TestController.php
[php]
        public function init()
        {
                $this->db = Zend_Registry::get('sysdb');
                $this->tpl = Zend_Registry::get('systpl');
                $this->baseUrl = $this->getRequest()->getBaseUrl();
                $this->host = "http://".$_SERVER['HTTP_HOST'];
        }

        public function fckAction()
        {
                $editor = new ORG_Editor_FCK('content');
                $editor->BasePath   = $this->host.'/vendor/fckeditor/';

                $editor->ToolbarSet = 'Basic';
                $editor->Width      = '400';
                $editor->Value='<h2>这个是一个测试!</h2><br>网站:<a href="http://www.mmocom.cn/">http://www.mmocom.cn/</a>';
                $editorHtml = $editor->Create();
                $this->tpl->assign('EditorHtml', $editorHtml);
                $this->tpl->display('test.html');
        }
       
        public function sinaAction()
        {
                $editor = new ORG_Editor_Sina('content');
                $editor->BasePath   = $this->host.'/vendor/sinaeditor/';
                $editor->Height='500';
                $editor->Width='700';
                $editor->Value='<h2>这个是一个测试!</h2><br>网站:<a href="http://www.mmocom.cn/">http://www.mmocom.cn/</a>';
                $editorHtml = $editor->Create();
                $this->tpl->assign('EditorHtml', $editorHtml);
                $this->tpl->display('test.html');
        }

[/php]

[[i] 本帖最后由 mmocom 于 2008-5-13 13:55 编辑 [/i]]

2008-5-13 13:54 mmocom
ORG_View类库

smarty文件放入ORG/View/目录下

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

class ORG_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);   
        }
       
       
        public function fetch($name)
        {
                return $this->_smarty->fetch($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);
        }

    }
       
}

?>[/php]

2008-5-13 23:43 jfcat
支持一个

2008-5-15 10:25 mayongzhan
更新完了?支持一个.非常强:victory:

2008-5-18 19:41 sailershen
请问楼主org类放在哪个目录下?
你说“smarty文件放入ORG/View/目录下”,那么这个ORG目录在哪个目录下?
你给出了TestController.php,但是请问IndexController.php文件有吗?
楼主能否给出完整的例子?

楼主的给的example很好,但是请楼主照顾初学者,请写的尽量详细,谢谢!

[[i] 本帖最后由 sailershen 于 2008-5-18 19:54 编辑 [/i]]

2008-5-26 15:26 sentrychen
初学ZF。。。有一个疑问,按照楼主的配置是不是意味着所有页面都会连接数据库?

2008-6-5 09:08 djw5215066
不顶一个对不起党了!LZ辛苦了!如果有更多的例子还请LZ继续来发帖。我帮你顶!:lol :lol :lol

2008-6-5 09:33 yhl_amerry
能把完整弄成一个包下载更好,呵呵,顶............

2008-6-5 14:17 lxydyx
谢谢了

2008-6-7 00:36 peacock
希望能出一个包下载

2008-6-13 09:56 maorenqi101
不是很详细,还是不懂,zF里面的文件放在哪里?

2008-6-13 09:57 maorenqi101
要是打个包给我们下载就好了

2008-6-13 14:18 wz_910
这样是不是好些
[php]
$view = new Custom_View_Smarty($extraParams);
$view->getEngine()->config_dir = '../app/config/';
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view);
$viewRenderer->setViewSuffix('html');
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
[/php]

2008-7-9 09:02 lino310
LZ辛苦了!!!!!

2008-8-12 15:58 lee_han
支持,去哪下载

2008-8-24 19:14 8liang
楼主辛苦了,顶

2008-9-4 15:42 deader
学习学习

页: [1] 2
查看完整版本: Zend Framework 1.5版本DEMO


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