代码改变世界

YII增加全局函数

2014-03-04 20:02  youxin  阅读(747)  评论(0编辑  收藏  举报

法1:

在使用Yii开发中我们经常会遇到一个问题,每次使用Yii的组件、扩展等,我们会像下面一样去写:

<?php
Yii::app()->user;
Yii::app()->getClientScript();
Yii::app()->params['name'];
...

这使我们用起来很不方便,我在 yiiFramework 上看到了一篇解决这个问题的 Wiki Use shortcut functions to reduce typing, 因为上面的英文很简单就不去翻译了,这里我只说明一下用法,创建全局文件 globals.php 把快捷函数放到这个全局文件里面。全局文件放到 protected 文件夹下面,然后在入口文件 `index.php' 引入

required('path/to/globals.php');

我推荐的是在配置文件 main.php' 里面引入,为了使console应用也能使用,配置文件console.php` 可修改为

return CMap::mergeArray(require('main.php'), array(
   // console 的配置
    ...
));

下面是官网上的一些快捷函数和我自己常用到的一些:

<?php
    /**
     * This is the shortcut to DIRECTORY_SEPARATOR
     */
    defined('DS') or define('DS', DIRECTORY_SEPARATOR);
 
    /**
     * This is the shortcut to Yii::app()
     *
     * @return CWebApplication
     */
    function app() {
        return Yii::app();
    }
 
    /**
     * This is the shortcut to Yii::app()->clientScript
     *
     * @return CClientScript
     */
    function cs() {
        return Yii::app()->getClientScript();
    }
 
    /**
     * This is the shortcut to Yii::app()->user.
     *
     * @return CWebUser
     */
    function user() {
        return Yii::app()->getUser();
    }
 
    /**
     * this is the shortcut to Yii::app()->createUrl().
     *
     * @param string $route
     * @param array $params
     * @param string $ampersand
     * @return string
     */
    function url($route, $params = array(), $ampersand = '&') {
        return Yii::app()->createUrl($route, $params, $ampersand);
    }
 
    /**
     * This is the shortcut to CHtml::encode
     *
     * @param string $text
     * @return string
     */
    function h($text) {
        return htmlspecialchars($text, ENT_QUOTES, Yii::app()->charset);
    }
 
    /**
     * This is the shortcut to CHtml::link().
     *
     * @param string $text
     * @param string|array $url
     * @param array $htmlOptions
     * @return string
     */
    function l($text, $url = '#', $htmlOptions = array()) {
        return CHtml::link($text, $url, $htmlOptions);
    }
 
    /**
     * This is the shortcut to Yii::t() with default category = 'stay'
     *
     * @param string $message
     * @param string $category
     * @param array $params
     * @param string $source
     * @param string $language
     * @return string
     */
    function t($message, $category = 'stay', $params = array(), $source = null, $language = null) {
        return Yii::t($category, $message, $params, $source, $language);
    }
 
    /**
     * This is the shortcut to Yii::app()->request->baseUrl
     * If the parameter is given, it will be returned and prefixed with the app baseUrl.
     *
     * @param string $url
     * @return string
     */
    function bu($url = null) {
        static $baseUrl;
        if ($baseUrl === null)
            $baseUrl = Yii::app()->getRequest()->getBaseUrl();
        return $url === null ? $baseUrl : $baseUrl . '/' . ltrim($url, '/');
    }
 
    /**
     * Returns the named application parameter.
     * This is the shortcut to Yii::app()->params[$name].
     *
     * @param string $name
     * @return mixed
     */
    function param($name) {
        return Yii::app()->params[$name];
    }
 
 
    // 下面是我用到的
 
    /**
     * 格式化函数,这是 Yii::app()->format 的快捷函数,使用方法
     *
     * <pre>
     * format($timestamp,'Datetime');
     * </pre>
     *
     * @param mixed $value
     * @param string $type 格式化的类型,如 'datetime', 'time'.., 详见 CFormatter
     * @return mixed
     */
    function format($value, $type) {
        return Yii::app()->format->format($value, $type);
    }
 
    /**
     * 这是加载模型的函数,如果没有找到模型则会抛出 404 错误
     *
     * @param string $modelName
     * @param integer $pk
     * @param string $errorMsg
     * @return CActiveRecord
     */
    function load_model($modelName, $pk, $errorMsg = null) {
        $model = $modelName::model()->findByPk((int)$pk);
        if ($model != null) {
            return $model;
        } else {
            throw new CHttpException(404, $errorMsg);
        }
    }
View Code

源码下载: 点击下载

我们还可以根据项目的具体需求添加

转自:http://www.yiiwiki.com/45/

法2:

是使用YII的类库

在protected\components下建立一个tool.php的静态类

代码如下

<?php  
class Tool {  
    public static function mkpath($path) {  
        $dirs = array();  
        $path = preg_replace('/(\/){2,}|(\\\){1,}/', '/', $path);  
        $dirs = explode("/", $path);  
        $path = "";  
        foreach ($dirs as $element) {  
            $path.=$element . "/";  
            if (!is_dir($path)) {  
                if (!mkdir($path, 0777)) {  
                    return false;  
                } else {  
                    chmod($path, 0777);  
                }  
            }  
        }  
        return true;  
    }  
    public static function test() {  
        echo('tetts');  
    }  
}  

然后控制器里面直接使用Tool::mkpath(xx/xx);

 

第一种方法最大的不好就是可能会出现冲突.