Input.class.php

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id: Input.class.php 2528 2012-01-03 14:58:50Z liu21st $

/*** 输入数据管理类
 * 使用方法
 *  $Input = Input::getInstance();
 *  $Input->get('name','md5','0');
 *  $Input->session('memberId','','0');
 *
 * 下面总结了一些常用的数据处理方法。以下方法无需考虑magic_quotes_gpc的设置。
 *
 * 获取数据:
 *    如果从$_POST或者$_GET中获取,使用Input::getVar($_POST['field']);,从数据库或者文件就不需要了。
 *    或者直接使用 Input::magicQuotes来消除所有的magic_quotes_gpc转义。
 *
 * 存储过程:
 *    经过Input::getVar($_POST['field'])获得的数据,就是干净的数据,可以直接保存。
 *    如果要过滤危险的html,可以使用 $html = Input::safeHtml($data);
 *
 * 页面显示:
 *    纯文本显示在网页中,如文章标题<title>$data</title>: $data = Input::forShow($field);
 *    HTML 在网页中显示,如文章内容:无需处理。
 *    在网页中以源代码方式显示html:$vo = Input::forShow($html);
 *    纯文本或者HTML在textarea中进行编辑: $vo = Input::forTarea($value);
 *    html在标签中使用,如<input value="数据" /> ,使用 $vo = Input::forTag($value); 或者 $vo = Input::hsc($value);
 *
 * 特殊使用情况:
 *    字符串要在数据库进行搜索: $data = Input::forSearch($field);
 */
class Input {

    private $filter =   null;   // 输入过滤
    private static $_input  =   array('get','post','request','env','server','cookie','session','globals','config','lang','call');
    //html标签设置
    public static $htmlTags = array(
        'allow' => 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a',
        'ban' => 'html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml',
    );

    static public function getInstance() {
        return get_instance_of(__CLASS__);
    }

    /***
     +----------------------------------------------------------
     * 魔术方法 有不存在的操作的时候执行
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $type 输入数据类型
     * @param array $args 参数 array(key,filter,default)
     +----------------------------------------------------------
     * @return mixed
     +----------------------------------------------------------
     */
    public function __call($type,$args=array()) {
        $type    =   strtolower(trim($type));
        if(in_array($type,self::$_input,true)) {
            switch($type) {
                case 'get':      $input      =& $_GET;break;
                case 'post':     $input      =& $_POST;break;
                case 'request': $input      =& $_REQUEST;break;
                case 'env':      $input      =& $_ENV;break;
                case 'server':   $input      =& $_SERVER;break;
                case 'cookie':   $input      =& $_COOKIE;break;
                case 'session':  $input      =& $_SESSION;break;
                case 'globals':   $input      =& $GLOBALS;break;
                case 'files':      $input      =& $_FILES;break;
                case 'call':       $input      =   'call';break;
                case 'config':    $input      =   C();break;
                case 'lang':      $input      =   L();break;
                default:return NULL;
            }
            if('call' === $input) {
                // 呼叫其他方式的输入数据
                $callback    =   array_shift($args);
                $params  =   array_shift($args);
                $data    =   call_user_func_array($callback,$params);
                if(count($args)===0) {
                    return $data;
                }
                $filter =   isset($args[0])?$args[0]:$this->filter;
                if(!empty($filter)) {
                    $data    =   call_user_func_array($filter,$data);
                }
            }else{
                if(0==count($args) || empty($args[0]) ) {
                    return $input;
                }elseif(array_key_exists($args[0],$input)) {
                    // 系统变量
                    $data	 =	 $input[$args[0]];
                    $filter	=	isset($args[1])?$args[1]:$this->filter;
                    if(!empty($filter)) {
                        $data	 =	 call_user_func_array($filter,$data);
                    }
                }else{
                    // 不存在指定输入
                    $data	 =	 isset($args[2])?$args[2]:NULL;
                }
            }
            return $data;
        }
    }

    /***
     +----------------------------------------------------------
     * 设置数据过滤方法
     +----------------------------------------------------------
     * @access private
     +----------------------------------------------------------
     * @param mixed $filter 过滤方法
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    public function filter($filter) {
        $this->filter   =   $filter;
        return $this;
    }

    /***
     +----------------------------------------------------------
     * 字符MagicQuote转义过滤
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    static public function noGPC() {
        if ( get_magic_quotes_gpc() ) {
           $_POST = stripslashes_deep($_POST);
           $_GET = stripslashes_deep($_GET);
           $_COOKIE = stripslashes_deep($_COOKIE);
           $_REQUEST= stripslashes_deep($_REQUEST);
        }
    }

    /***
     +----------------------------------------------------------
     * 处理字符串,以便可以正常进行搜索
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function forSearch($string) {
        return str_replace( array('%','_'), array('\%','\_'), $string );
    }

    /***
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function forShow($string) {
        return self::nl2Br( self::hsc($string) );
    }

    /***
     +----------------------------------------------------------
     * 处理纯文本数据,以便在textarea标签中显示
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function forTarea($string) {
        return str_ireplace(array('<textarea>','</textarea>'), array('<textarea>','</textarea>'), $string);
    }

    /***
     +----------------------------------------------------------
     * 将数据中的单引号和双引号进行转义
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $text 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function forTag($string) {
        return str_replace(array('"',"'"), array('"','''), $string);
    }

    /***
     +----------------------------------------------------------
     * 转换文字中的超链接为可点击连接
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function makeLink($string) {
        $validChars = "a-z0-9\/\-_+=.~!%@?#&;:$\|";
        $patterns = array(
                        "/(^|[^]_a-z0-9-=\"'\/])([a-z]+?):\/\/([{$validChars}]+)/ei",
                        "/(^|[^]_a-z0-9-=\"'\/])www\.([a-z0-9\-]+)\.([{$validChars}]+)/ei",
                        "/(^|[^]_a-z0-9-=\"'\/])ftp\.([a-z0-9\-]+)\.([{$validChars}]+)/ei",
                        "/(^|[^]_a-z0-9-=\"'\/:\.])([a-z0-9\-_\.]+?)@([{$validChars}]+)/ei");
        $replacements = array(
                        "'\\1<a href=\"\\2://\\3\" title=\"\\2://\\3\" rel=\"external\">\\2://'.Input::truncate( '\\3' ).'</a>'",
                        "'\\1<a href=\"http://www.\\2.\\3\" title=\"www.\\2.\\3\" rel=\"external\">'.Input::truncate( 'www.\\2.\\3' ).'</a>'",
                        "'\\1<a href=\"ftp://ftp.\\2.\\3\" title=\"ftp.\\2.\\3\" rel=\"external\">'.Input::truncate( 'ftp.\\2.\\3' ).'</a>'",
                        "'\\1<a href=\"mailto:\\2@\\3\" title=\"\\2@\\3\">'.Input::truncate( '\\2@\\3' ).'</a>'");
        return preg_replace($patterns, $replacements, $string);
    }

    /***
     +----------------------------------------------------------
     * 缩略显示字符串
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     * @param int $length 缩略之后的长度
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function truncate($string, $length = '50') {
        if ( empty($string) || empty($length) || strlen($string) < $length ) return $string;
        $len = floor( $length / 2 );
        $ret = substr($string, 0, $len) . " ... ". substr($string, 5 - $len);
        return $ret;
    }

    /***
     +----------------------------------------------------------
     * 把换行转换为<br />标签
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function nl2Br($string) {
        return preg_replace("/(\015\012)|(\015)|(\012)/", "<br />", $string);
    }

    /***
     +----------------------------------------------------------
     * 如果 magic_quotes_gpc 为关闭状态,这个函数可以转义字符串
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function addSlashes($string) {
        if (!get_magic_quotes_gpc()) {
            $string = addslashes($string);
        }
        return $string;
    }

    /***
     +----------------------------------------------------------
     * 从$_POST,$_GET,$_COOKIE,$_REQUEST等数组中获得数据
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function getVar($string) {
        return Input::stripSlashes($string);
    }

    /***
     +----------------------------------------------------------
     * 如果 magic_quotes_gpc 为开启状态,这个函数可以反转义字符串
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function stripSlashes($string) {
        if (get_magic_quotes_gpc()) {
            $string = stripslashes($string);
        }
        return $string;
    }

    /***
     +----------------------------------------------------------
     * 用于在textbox表单中显示html代码
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static function hsc($string) {
        return preg_replace(array("/&/i", "/ /i"), array('&', '&nbsp;'), htmlspecialchars($string, ENT_QUOTES));
    }

    /***
     +----------------------------------------------------------
     * 是hsc()方法的逆操作
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $text 要处理的字符串
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static function undoHsc($text) {
        return preg_replace(array("/>/i", "/</i", "/"/i", "/'/i", '/&nbsp;/i'), array(">", "<", "\"", "'", " "), $text);
    }

    /***
     +----------------------------------------------------------
     * 输出安全的html,用于过滤危险代码
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $text 要处理的字符串
     * @param mixed $allowTags 允许的标签列表,如 table|td|th|td
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function safeHtml($text, $allowTags = null) {
        $text =  trim($text);
        //完全过滤注释
        $text = preg_replace('/<!--?.*-->/','',$text);
        //完全过滤动态代码
        $text =  preg_replace('/<\?|\?'.'>/','',$text);
        //完全过滤js
        $text = preg_replace('/<script?.*\/script>/','',$text);

        $text =  str_replace('[','[',$text);
        $text = str_replace(']',']',$text);
        $text =  str_replace('|','|',$text);
        //过滤换行符
        $text = preg_replace('/\r?\n/','',$text);
        //br
        $text =  preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
        $text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
        //过滤危险的属性,如:过滤on事件lang js
        while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
            $text=str_replace($mat[0],$mat[1],$text);
        }
        while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
            $text=str_replace($mat[0],$mat[1].$mat[3],$text);
        }
        if( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
        //允许的HTML标签
        $text =  preg_replace('/<('.$allowTags.')( [^><\[\]]*)>/i','[\1\2]',$text);
        //过滤多余html
        if ( empty($banTag) ) { $banTag = self::$htmlTags['ban']; }
        $text =  preg_replace('/<\/?('.$banTag.')[^><]*>/i','',$text);
        //过滤合法的html标签
        while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
            $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
        }
        //转换引号
        while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
            $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
        }
        //空属性转换
        $text =  str_replace('\'\'','||',$text);
        $text = str_replace('""','||',$text);
        //过滤错误的单个引号
        while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
            $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
        }
        //转换其它所有不合法的 < >
        $text =  str_replace('<','<',$text);
        $text = str_replace('>','>',$text);
        $text = str_replace('"','"',$text);
        //反转换
        $text =  str_replace('[','<',$text);
        $text =  str_replace(']','>',$text);
        $text =  str_replace('|','"',$text);
        //过滤多余空格
        $text =  str_replace('  ',' ',$text);
        return $text;
    }

    /***
     +----------------------------------------------------------
     * 删除html标签,得到纯文本。可以处理嵌套的标签
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的html
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function deleteHtmlTags($string) {
        while(strstr($string, '>')) {
            $currentBeg = strpos($string, '<');
            $currentEnd = strpos($string, '>');
            $tmpStringBeg = @substr($string, 0, $currentBeg);
            $tmpStringEnd = @substr($string, $currentEnd + 1, strlen($string));
            $string = $tmpStringBeg.$tmpStringEnd;
        }
        return $string;
    }

    /***
     +----------------------------------------------------------
     * 处理文本中的换行
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的字符串
     * @param mixed $br 对换行的处理,
     *        false:去除换行;true:保留原样;string:替换成string
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    static public function nl2($string, $br = '<br />') {
        if ($br == false) {
            $string = preg_replace("/(\015\012)|(\015)|(\012)/", '', $string);
        } elseif ($br != true){
            $string = preg_replace("/(\015\012)|(\015)|(\012)/", $br, $string);
        }
        return $string;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Table of Contents Introduction....................................................................................................13 Code Examples........................................................................................................13 What is Doctrine?....................................................................................................13 What is an ORM?.....................................................................................................13 What is the Problem?...............................................................................................13 Minimum Requirements..........................................................................................14 Basic Overview........................................................................................................14 Doctrine Explained..................................................................................................15 Key Concepts...........................................................................................................16 Further Reading......................................................................................................17 Conclusion...............................................................................................................17 Getting Started...............................................................................................18 Checking Requirements...........................................................................................18 Installing..................................................................................................................19 Sandbox..............................................................................................................................19 SVN.....................................................................................................................................19 Installing.........................................................................................................................................19 Updating.........................................................................................................................................20 SVN Externals....................................................................................................................20 PEAR Installer....................................................................................................................20 Download Pear Package.....................................................................................................21 Implementing...........................................................................................................21 Including Doctrine Libraries..............................................................................................21 Require Doctrine Base Class..............................................................................................21 Register Autoloader............................................................................................................22 Autoloading Explained....................................................................................................................22 Bootstrap File.....................................................................................................................23 Test Script..........................................................................................................................23 Conclusion...............................................................................................................24 Introduction to Connections...........................................................................25 DSN, the Data Source Name...................................................................................25 Examples............................................................................................................................27 Opening New Connections......................................................................................27 Lazy Database Connecting......................................................................................28 Testing your Connection..........................................................................................28 Conclusion...............................................................................................................29 Configuration..................................................................................................30 Levels of Configuration............................................................................................30 Portability................................................................................................................31 Portability Mode Attributes................................................................................................31 Table of Contents ii ----------------- Brought to you by Examples............................................................................................................................32 Identifier quoting.....................................................................................................32 Exporting.................................................................................................................33 Naming convention attributes.................................................................................34 Index name format.............................................................................................................34 Sequence name format.......................................................................................................34 Table name format.............................................................................................................34 Database name format.......................................................................................................34 Validation attributes...........................................................................................................35 Validation mode constants.................................................................................................35 Examples............................................................................................................................35 Optional String Syntax............................................................................................35 Conclusion...............................................................................................................36 Connections....................................................................................................37 Introduction.............................................................................................................37 Opening Connections...............................................................................................37 Retrieve Connections...............................................................................................37 Current Connection.................................................................................................38 Change Current Connection....................................................................................38 Iterating Connections..............................................................................................38 Get Connection Name..............................................................................................38 Close Connection.....................................................................................................39 Get All Connections.................................................................................................39 Count Connections...................................................................................................40 Creating and Dropping Database............................................................................40 Conclusion...............................................................................................................40 Introduction to Models...................................................................................42 Introduction.............................................................................................................42 Generating Models..................................................................................................42 Existing Databases.............................................................................................................43 Making the first import...................................................................................................................43 Schema Files......................................................................................................................46 Manually Writing Models........................................................................................48 Autoloading Models.................................................................................................48 Conservative.......................................................................................................................48 Aggressive..........................................................................................................................49 Conclusion...............................................................................................................50 Defining Models..............................................................................................51 Columns...................................................................................................................51 Column Lengths.................................................................................................................51 Column Aliases...................................................................................................................52 Default values.....................................................................................................................52 Data types...........................................................................................................................53 Introduction....................................................................................................................................53 Type modifiers................................................................................................................................54 Boolean...........................................................................................................................................54 Integer............................................................................................................................................55 Float................................................................................................................................................55 Decimal...........................................................................................................................................56 String..............................................................................................................................................57 Array...............................................................................................................................................57 Object.............................................................................................................................................58 Table of Contents iii ----------------- Brought to you by Blob.................................................................................................................................................58 Clob.................................................................................................................................................58 Timestamp......................................................................................................................................59 Time................................................................................................................................................59 Date................................................................................................................................................60 Enum...............................................................................................................................................60 Gzip.................................................................................................................................................61 Examples............................................................................................................................61 Relationships...........................................................................................................64 Introduction........................................................................................................................64 Foreign Key Associations...................................................................................................69 One to One......................................................................................................................................69 One to Many and Many to One.......................................................................................................70 Tree Structure................................................................................................................................72 Join Table Associations.......................................................................................................73 Many to Many.................................................................................................................................73 Self Referencing (Nest Relations)..................................................................................................77 Non-Equal Nest Relations............................................................................................................................77 Equal Nest Relations....................................................................................................................................78 Foreign Key Constraints.....................................................................................................80 Introduction....................................................................................................................................80 Integrity Actions.............................................................................................................................82 Indexes.....................................................................................................................84 Introduction........................................................................................................................84 Adding indexes...................................................................................................................84 Index options......................................................................................................................86 Special indexes...................................................................................................................87 Checks.....................................................................................................................87 Table Options...........................................................................................................88 Transitive Persistence.............................................................................................89 Application-Level Cascades................................................................................................89 Save Cascades................................................................................................................................90 Delete Cascades..............................................................................................................................90 Database-Level Cascades...................................................................................................91 Conclusion...............................................................................................................92 Working with Models......................................................................................93 Define Test Schema.................................................................................................93 Dealing with Relations.............................................................................................97 Creating Related Records..................................................................................................97 Retrieving Related Records................................................................................................99 Updating Related Records................................................................................................100 Deleting Related Records.................................................................................................100 Working with Related Records.........................................................................................101 Testing the Existence of a Relation..............................................................................................101 Many-to-Many Relations........................................................................................102 Creating a New Link.........................................................................................................102 Deleting a Link.................................................................................................................102 Fetching Objects....................................................................................................103 Sample Queries................................................................................................................105 Field Lazy Loading...........................................................................................................111 Arrays and Objects................................................................................................112 To Array............................................................................................................................112 From Array.......................................................................................................................112 Synchronize With Array....................................................................................................112 Overriding the Constructor...................................................................................113 Conclusion.............................................................................................................114 Table of Contents iv ----------------- Brought to you by DQL (Doctrine Query Language)..................................................................115 Introduction...........................................................................................................115 SELECT queries.....................................................................................................117 Aggregate values..............................................................................................................121 UPDATE queries....................................................................................................122 DELETE Queries....................................................................................................123 FROM clause.........................................................................................................124 JOIN syntax............................................................................................................124 ON keyword......................................................................................................................126 WITH keyword..................................................................................................................126 INDEXBY keyword.................................................................................................127 WHERE clause.......................................................................................................128 Conditional expressions.........................................................................................129 Literals.............................................................................................................................129 Input parameters..............................................................................................................131 Operators and operator precedence................................................................................132 In expressions...................................................................................................................133 Like Expressions...............................................................................................................134 Exists Expressions............................................................................................................135 All and Any Expressions...................................................................................................137 Subqueries........................................................................................................................137 Functional Expressions..........................................................................................139 String functions................................................................................................................139 Arithmetic functions.........................................................................................................141 Subqueries.............................................................................................................141 Introduction......................................................................................................................141 Comparisons using subqueries.........................................................................................141 GROUP BY, HAVING clauses.................................................................................142 ORDER BY clause..................................................................................................144 Introduction......................................................................................................................144 Sorting by an aggregate value.........................................................................................145 Using random order.........................................................................................................145 LIMIT and OFFSET clauses...................................................................................146 Driver Portability..............................................................................................................146 The limit-subquery-algorithm...........................................................................................147 Named Queries......................................................................................................148 Creating a Named Query..................................................................................................149 Accessing Named Query...................................................................................................149 Executing a Named Query................................................................................................150 Cross-Accessing Named Query........................................................................................150 BNF........................................................................................................................150 Magic Finders........................................................................................................154 Debugging Queries................................................................................................155 Conclusion.............................................................................................................155 Component Overview....................................................................................156 Manager.................................................................................................................156 Retrieving Connections....................................................................................................156 Connection.............................................................................................................157 Available Drivers..............................................................................................................157 Creating Connections.......................................................................................................157 Flushing the Connection..................................................................................................157 Table......................................................................................................................158 Table of Contents v ----------------- Brought to you by Getting a Table Object......................................................................................................158 Getting Column Information.............................................................................................158 Getting Relation Information............................................................................................159 Finder Methods................................................................................................................161 Custom Table Classes...................................................................................................................162 Custom Finders................................................................................................................162 Record....................................................................................................................163 Properties.........................................................................................................................163 Updating Records.............................................................................................................166 Replacing Records............................................................................................................167 Refreshing Records..........................................................................................................167 Refreshing relationships...................................................................................................168 Deleting Records..............................................................................................................169 Using Expression Values..................................................................................................170 Getting Record State........................................................................................................170 Getting Object Copy.........................................................................................................171 Saving a Blank Record.....................................................................................................172 Mapping Custom Values...................................................................................................172 Serializing.........................................................................................................................172 Checking Existence..........................................................................................................172 Function Callbacks for Columns......................................................................................173 Collection...............................................................................................................173 Accessing Elements..........................................................................................................173 Adding new Elements.......................................................................................................174 Getting Collection Count..................................................................................................174 Saving the Collection........................................................................................................175 Deleting the Collection.....................................................................................................175 Key Mapping.....................................................................................................................175 Loading Related Records.................................................................................................176 Validator................................................................................................................177 More Validation................................................................................................................178 Valid or Not Valid.............................................................................................................179 Implicit Validation........................................................................................................................179 Explicit Validation.........................................................................................................................179 Profiler...................................................................................................................180 Basic Usage......................................................................................................................181 Locking Manager...................................................................................................181 Optimistic Locking...........................................................................................................181 Pessimistic Locking..........................................................................................................182 Examples..........................................................................................................................182 Technical Details..............................................................................................................183 Views......................................................................................................................183 Using Views......................................................................................................................183 Conclusion.............................................................................................................184 Native SQL....................................................................................................185 Introduction...........................................................................................................185 Component Queries...............................................................................................185 Fetching from Multiple Components.....................................................................186 Conclusion.............................................................................................................187 YAML Schema Files.......................................................................................188 Introduction...........................................................................................................188 Abbreviated Syntax................................................................................................188 Verbose Syntax......................................................................................................189 Table of Contents vi ----------------- Brought to you by Relationships.........................................................................................................189 Detect Relations...............................................................................................................190 Customizing Relationships...............................................................................................190 One to One........................................................................................................................191 One to Many.....................................................................................................................191 Many to Many...................................................................................................................192 Features & Examples.............................................................................................193 Connection Binding..........................................................................................................193 Attributes..........................................................................................................................193 Enums...............................................................................................................................194 ActAs Behaviors................................................................................................................194 Listeners...........................................................................................................................195 Options.............................................................................................................................196 Indexes.............................................................................................................................196 Inheritance.......................................................................................................................197 Simple Inheritance.......................................................................................................................197 Concrete Inheritance....................................................................................................................197 Column Aggregation Inheritance.................................................................................................198 Column Aliases.................................................................................................................199 Packages...........................................................................................................................199 Package Custom Path...................................................................................................................199 Global Schema Information..............................................................................................199 Using Schema Files...............................................................................................200 Conclusion.............................................................................................................201 Data Validation.............................................................................................202 Introduction...........................................................................................................202 Examples................................................................................................................204 Not Null............................................................................................................................204 Email.................................................................................................................................205 Not Blank..........................................................................................................................206 No Space..........................................................................................................................207 Past...................................................................................................................................208 Future...............................................................................................................................208 Min Length.......................................................................................................................209 Country.............................................................................................................................210 IP Address........................................................................................................................211 HTML Color......................................................................................................................212 Range................................................................................................................................213 Unique..............................................................................................................................214 Regular Expression..........................................................................................................215 Credit Card.......................................................................................................................216 Read Only.........................................................................................................................217 Unsigned..........................................................................................................................217 US State...........................................................................................................................218 Conclusion.............................................................................................................219 Inheritance....................................................................................................220 Simple....................................................................................................................220 Concrete................................................................................................................221 Column Aggregation..............................................................................................224 Conclusion.............................................................................................................227 Behaviors......................................................................................................228 Introduction...........................................................................................................228 Simple Templates..................................................................................................229 Table of Contents vii ----------------- Brought to you by Templates with Relations......................................................................................230 Delegate Methods..................................................................................................234 Creating Behaviors................................................................................................235 Core Behaviors......................................................................................................236 Introduction......................................................................................................................236 Versionable.......................................................................................................................236 Timestampable.................................................................................................................238 Sluggable..........................................................................................................................240 I18n..................................................................................................................................242 NestedSet.........................................................................................................................244 Searchable........................................................................................................................246 Geographical....................................................................................................................247 SoftDelete.........................................................................................................................250 Nesting Behaviors..................................................................................................252 Generating Files....................................................................................................253 Querying Generated Classes.................................................................................254 Conclusion.............................................................................................................255 Searching......................................................................................................256 Introduction...........................................................................................................256 Index structure......................................................................................................258 Index Building........................................................................................................258 Text Analyzers.......................................................................................................259 Query language......................................................................................................260 Performing Searches.............................................................................................260 File searches..........................................................................................................263 Conclusion.............................................................................................................264 Hierarchical Data..........................................................................................265 Introduction...........................................................................................................265 Nested Set.............................................................................................................266 Introduction......................................................................................................................266 Setting Up........................................................................................................................266 Multiple Trees..................................................................................................................267 Working with Trees..........................................................................................................267 Creating a Root Node...................................................................................................................268 Inserting a Node...........................................................................................................................268 Deleting a Node............................................................................................................................268 Moving a Node..............................................................................................................................269 Examining a Node.........................................................................................................................269 Examining and Retrieving Siblings..............................................................................................270 Examining and Retrieving Descendants.......................................................................................270 Rendering a Simple Tree..............................................................................................................271 Advanced Usage...............................................................................................................271 Fetching a Tree with Relations.....................................................................................................272 Rendering with Indention.................................................................................................273 Conclusion.............................................................................................................273 Data Fixtures.................................................................................................274 Importing...............................................................................................................274 Dumping................................................................................................................274 Implement..............................................................................................................275 Writing...................................................................................................................275 Fixtures For Nested Sets.......................................................................................279 Fixtures For I18n...................................................................................................280 Table of Contents viii ----------------- Brought to you by Conclusion.............................................................................................................280 Database Abstraction Layer..........................................................................281 Export....................................................................................................................281 Introduction......................................................................................................................281 Creating Databases..........................................................................................................282 Creating Tables................................................................................................................282 Creating Foreign Keys......................................................................................................284 Altering table....................................................................................................................285 Creating Indexes..............................................................................................................287 Deleting database elements.............................................................................................287 Import....................................................................................................................288 Introduction......................................................................................................................288 Listing Databases.............................................................................................................289 Listing Sequences............................................................................................................289 Listing Constraints...........................................................................................................289 Listing Table Columns......................................................................................................289 Listing Table Indexes.......................................................................................................289 Listing Tables...................................................................................................................290 Listing Views....................................................................................................................290 DataDict.................................................................................................................290 Introduction......................................................................................................................290 Getting portable declaration............................................................................................290 Getting Native Declaration...............................................................................................291 Drivers...................................................................................................................291 Mysql................................................................................................................................291 Setting table type.........................................................................................................................291 Conclusion.............................................................................................................292 Transactions..................................................................................................293 Introduction...........................................................................................................293 Nesting..................................................................................................................294 Savepoints.............................................................................................................295 Isolation Levels......................................................................................................296 Conclusion.............................................................................................................297 Event Listeners.............................................................................................298 Introduction...........................................................................................................298 Connection Listeners.............................................................................................299 Creating a New Listener..................................................................................................299 Attaching listeners...........................................................................................................300 Pre and Post Connect.......................................................................................................300 Transaction Listeners.......................................................................................................301 Query Execution Listeners...............................................................................................301 Hydration Listeners...............................................................................................302 Record Listeners....................................................................................................303 Record Hooks.........................................................................................................304 DQL Hooks.............................................................................................................305 Chaining Listeners.................................................................................................308 The Event object....................................................................................................308 Getting the Invoker..........................................................................................................308 Event Codes......................................................................................................................308 Getting the Invoker..........................................................................................................308 Skip Next Operation.........................................................................................................309 Skip Next Listener............................................................................................................310 Table of Contents ix ----------------- Brought to you by Conclusion.............................................................................................................310 Caching.........................................................................................................311 Introduction...........................................................................................................311 Drivers...................................................................................................................311 Memcache........................................................................................................................311 APC...................................................................................................................................312 Db.....................................................................................................................................312 Query Cache & Result Cache................................................................................313 Introduction......................................................................................................................313 Query Cache.....................................................................................................................313 Using the Query Cache.................................................................................................................313 Fine Tuning...................................................................................................................................314 Result Cache.....................................................................................................................314 Using the Result Cache................................................................................................................314 Fine Tuning...................................................................................................................................315 Conclusion.............................................................................................................315 Migrations.....................................................................................................316 Performing Migrations..........................................................................................316 Implement..............................................................................................................317 Writing Migration Classes.....................................................................................317 Available Operations........................................................................................................319 Create Table.................................................................................................................................319 Drop Table....................................................................................................................................319 Rename Table...............................................................................................................................320 Create Constraint.........................................................................................................................320 Drop Constraint............................................................................................................................320 Create Foreign Key.......................................................................................................................320 Drop Foreign Key..........................................................................................................................321 Add Column..................................................................................................................................321 Rename Column............................................................................................................................321 Change Column............................................................................................................................321 Remove Column............................................................................................................................322 Irreversible Migration..................................................................................................................322 Add Index......................................................................................................................................322 Remove Index...............................................................................................................................322 Pre and Post Hooks..........................................................................................................322 Generating Migrations.....................................................................................................323 From Database.............................................................................................................................324 From Existing Models...................................................................................................................324 Conclusion.............................................................................................................324 Utilities..........................................................................................................325 Pagination..............................................................................................................325 Introduction......................................................................................................................325 Working with Pager..........................................................................................................325 Controlling Range Styles..................................................................................................327 Sliding...........................................................................................................................................328 Jumping.........................................................................................................................................328 Advanced layouts with pager...........................................................................................329 Mask.............................................................................................................................................329 Template.......................................................................................................................................330 Customizing pager layout.................................................................................................332 Facade...................................................................................................................335 Creating & Dropping Databases......................................................................................335 Convenience Methods......................................................................................................335 Tasks.................................................................................................................................337 Table of Contents x ----------------- Brought to you by Command Line Interface.......................................................................................338 Introduction......................................................................................................................338 Tasks.................................................................................................................................338 Usage................................................................................................................................339 Sandbox.................................................................................................................339 Installation........................................................................................................................339 Conclusion.............................................................................................................340 Unit Testing..................................................................................................341 Running tests.........................................................................................................341 CLI....................................................................................................................................341 Browser............................................................................................................................342 Writing Tests.........................................................................................................342 Ticket Tests......................................................................................................................343 Methods for testing..........................................................................................................343 Assert Equal..................................................................................................................................343 Assert Not Equal...........................................................................................................................344 Assert Identical.............................................................................................................................344 Assert True...................................................................................................................................344 Assert False..................................................................................................................................344 Mock Drivers....................................................................................................................344 Test Class Guidelines.......................................................................................................345 Test Method Guidelines....................................................................................................345 Conclusion.............................................................................................................346 Improving Performance................................................................................347 Introduction...........................................................................................................347 Compile..................................................................................................................347 Conservative Fetching...........................................................................................348 Bundle your Class Files.........................................................................................350 Use a Bytecode Cache...........................................................................................350 Free Objects...........................................................................................................350 Other Tips..............................................................................................................351 Conclusion.............................................................................................................352 Technology....................................................................................................353 Introduction...........................................................................................................353 Architecture...........................................................................................................353 Doctrine CORE.................................................................................................................353 Doctrine DBAL..................................................................................................................354 Doctrine ORM...................................................................................................................354 Design Patterns Used............................................................................................354 Speed.....................................................................................................................355 Conclusion.............................................................................................................356 Exceptions and Warnings.............................................................................357 Manager exceptions...............................................................................................357 Relation exceptions.............................
AJAX is a complex phenomenon that means different things to different people. Computer users appreciate that their favorite websites are now friendlier and feel more responsive. Web developers learn new skills that empower them to create sleek web applications with little effort. Indeed, everything sounds good about AJAX! At its roots, AJAX is a mix of technologies that lets you get rid of the evil page reload, which represents the dead time when navigating from one page to another. Eliminating page reloads is just one step away from enabling more complex features into websites, such as real-time data validation, drag-and-drop, and other tasks that weren't traditionally associated with web applications. Although the AJAX ingredients are mature (the XMLHttpRequest object, which is the heart of AJAX, was created by Microsoft in 1999), their new role in the new wave of web trends is very young, and we'll witness a number of changes before these technologies will be properly used to the best benefit of the end users. AJAX isn't, of course, the answer to all the Web's problems, as the current hype around it may suggest. As with any other technology, AJAX can be overused, or used the wrong way. AJAX also comes with problems of its own: you need to fight with browser inconsistencies, AJAX-specific pages don't work on browsers without JavaScript, they can't be easily bookmarked by users, and search engines don't always know how to parse them. Also, not everyone likes AJAX. While some are developing enterprise architectures using JavaScript, others prefer not to use it at all. When the hype is over, most will probably agree that the middle way is the wisest way to go for most scenarios. In AJAX and PHP: Building Modern Web Applications – Second Edition, we take a pragmatic and safe approach by teaching relevant patterns and best practices that we think any web developer will need sooner or later. We teach you how to avoid the common pitfalls, how to write efficient AJAX code, and how to achieve functionality that is easy to integrate into current and future web applications, without requiring you to rebuild the whole solution around AJAX. You'll be able to use the knowledge you learn from this book right away, in your PHP web applications. What this book covers Chapter 1: The World of AJAX and PHP is all about a quick introduction to the world of AJAX. In order to proceed with learning how to build AJAX applications, it's important to understand why and where they are useful. It describes the XMLHttpRequest object, which is the key element that enables the client-side JavaScript code to call a page on the server asynchronously. Chapter 2: JavaScript and the AJAX Client walks you through many fields such as working with HTML, JavaScript, CSS, the DOM, XML, and XMLHttpRequest. It discusses the theory (and practice) that you will need to know to make these components come together smoothly, and form a solid foundation for your future AJAX applications. It also shows you how to implement simple error-handling techniques, and how to write code efficiently. Chapter 3: Object Oriented JavaScript covers a large area of what object-oriented programming means in the world of JavaScript starting from basic features and going far into the execution context of functions. It teaches you the basic OOP concepts—encapsulation, polymorphism, and inheritance, how to work with JavaScript objects, functions, classes, and prototypes, how to simulate private, instance, and static class members in JavaScript, what the JavaScript execution context is, how to implement inheritance by using constructor functions and prototyping, and the basics of JSON. Chapter 4: Using PHP and MySQL on the Server starts putting the server to work, using PHP to generate dynamic output, and MySQL to manipulate and store the backend data. This chapter shows you how to use XML and JSON with PHP (so that you can create server-side code that communicates with your JavaScript client), how to implement error-handling code in your server-side PHP code, and how to work with MySQL databases. Chapter 5: AJAX Form Validation creates a form validation application that implements traditional techniques with added AJAX flavor, thereby making the form more user-friendly, responsive, and pleasing. The intention of this chapter isn't to build the perfect validation technique but, rather, a working proof of concept that takes care of user input and ensures its validity. Chapter 6: Debugging and Profiling AJAX Applications teaches how to enable and use Internet Explorer's debugging capabilities. It shows how you can work with Web Development Helper, Developer Toolbar, and other Internet Explorer tools and with Firefox plugins such as Firebug, Venkman JavaScript Debugger, and Web Developer. This material is copyright and is licensed for the sole use by ALESSANDRO CAROLLO on 18th December 2009 6393 south jamaica court, , englewood, , 80111 Preface [ 3 ] Chapter 7: Advanced Patterns and Techniques briefly covers some of the most important patterns and techniques covering usability, security, and techniques. Looking at methods, patterns, and techniques is so important that it has developed into its own science and has created a set of guidelines for typical problems that offer us predictable results. Chapter 8: AJAX Chat with jQuery teaches how to use AJAX to easily implement an online chat solution. This will also be your opportunity to use one of the most important JavaScript frameworks around—jQuery. More precisely, this chapter will explain the basics of jQuery and show how to create a simple, yet efficient client- server chat mechanism using AJAX. Chapter 9: AJAX Grid explains the usage of an AJAX-enabled data grid plugin, jqGrid. Appendix: Preparing Your Working Environment covers the installation instructions that set up your machine for the exercises in this book. It also covers preparing the database that is used in many examples throughout the book. What you need for this book To go through the examples in this book you need PHP 5, a web server, and a database server. We have tested the code under several environments, but mostly with the Apache 2 web server, and MySQL 4.1 and MySQL 5 databases. You can choose, however, to use another web server, or another database product, in which case the procedures presented in the chapters might not be 100% accurate. It is important to have PHP 5 or newer, because we use some features, such as Object Oriented Programming support, which aren't available in older versions. Please read the appendix for more details about setting up your machine. If your machine already has the required software, you still need to read the final part of appendix, where you are instructed about creating a database that is used for the examples in this book. Who this book is for This book is written for PHP developers who want to learn how to use PHP, JavaScript, MySQL, and jQuery to implement Web 2.0 applications, are looking for a step-by-step, example-driven AJAX tutorial, want to learn advanced AJAX coding patterns and techniques, and want to be able to assess the security and SEO implications of their code.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值