diff --git a/.gitignore b/.gitignore index 31653af0018b..656f6ee1e87f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ build en/_build +zh/_build _templates *.komodoproject *.sublime-* -.idea/ \ No newline at end of file +.idea/ diff --git a/en/_static/docs.css b/en/_static/docs.css index e89754aab9ee..3b06b512e00c 100755 --- a/en/_static/docs.css +++ b/en/_static/docs.css @@ -26,6 +26,11 @@ h2 { margin: 25px 0 0; } +h3 { + font-weight: 600; + margin: 15px 0 10px; +} + /*p, li { color: #434343; }*/ @@ -462,6 +467,15 @@ div.highlight { font-weight: bold; } +.highlight .kn { + color: #000000; + font-weight: normal; +} + +.highlight .sr { + color: #717171; +} + pre { font-family: Monaco,Menlo,Consolas,"Courier New",monospace; -} \ No newline at end of file +} diff --git a/en/_static/img/volt-bundle.jpg b/en/_static/img/volt-bundle.jpg new file mode 100644 index 000000000000..55936088e88d Binary files /dev/null and b/en/_static/img/volt-bundle.jpg differ diff --git a/en/_static/img/volt.jpg b/en/_static/img/volt.jpg new file mode 100644 index 000000000000..b2da5577fc47 Binary files /dev/null and b/en/_static/img/volt.jpg differ diff --git a/en/api/Phalcon_Acl_AdapterInterface.rst b/en/api/Phalcon_Acl_AdapterInterface.rst index 745379de5226..779d0f291b6c 100644 --- a/en/api/Phalcon_Acl_AdapterInterface.rst +++ b/en/api/Phalcon_Acl_AdapterInterface.rst @@ -19,7 +19,7 @@ Returns the default ACL access level -abstract public *boolean* **addRole** (:doc:`Phalcon\\Mvc\\RoleInterface ` $roleObject, *array* $accessInherits) +abstract public *boolean* **addRole** (:doc:`Phalcon\\Acl\\RoleInterface ` $roleObject, *array* $accessInherits) Adds a role to the ACL list. Second parameter lets to inherit access data from other existing role diff --git a/en/api/Phalcon_CLI_Dispatcher.rst b/en/api/Phalcon_CLI_Dispatcher.rst index ee418cc26c97..efbffcdfd995 100644 --- a/en/api/Phalcon_CLI_Dispatcher.rst +++ b/en/api/Phalcon_CLI_Dispatcher.rst @@ -121,6 +121,18 @@ Sets the default action suffix +public **setNamespaceName** (*string* $namespaceName) inherited from Phalcon\\Dispatcher + +Sets a namespace to be prepended to the handler name + + + +public *string* **getNamespaceName** () inherited from Phalcon\\Dispatcher + +Gets a namespace to be prepended to the current handler name + + + public **setDefaultNamespace** (*string* $namespace) inherited from Phalcon\\Dispatcher Sets the default namespace @@ -169,7 +181,7 @@ Set a param by its name or numeric index -public *mixed* **getParam** (*mixed* $param, *string|array* $filters) inherited from Phalcon\\Dispatcher +public *mixed* **getParam** (*mixed* $param, *string|array* $filters, *mixed* $defaultValue) inherited from Phalcon\\Dispatcher Gets a param by its name or numeric index diff --git a/en/api/Phalcon_Cache_Backend.rst b/en/api/Phalcon_Cache_Backend.rst index c4d24ead4169..77e0072512a5 100755 --- a/en/api/Phalcon_Cache_Backend.rst +++ b/en/api/Phalcon_Cache_Backend.rst @@ -7,7 +7,7 @@ This class implements common functionality for backend adapters. All the backend Methods --------- -public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontendObject, *array* $backendOptions) +public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontend, *array* $options) Phalcon\\Cache\\Backend constructor @@ -31,6 +31,12 @@ Returns front-end instance adapter related to the back-end +public *array* **getOptions** () + +Returns the backend options + + + public *boolean* **isFresh** () Checks whether the last cache is fresh or cached @@ -43,14 +49,15 @@ Checks whether the cache has starting buffering or not -public *string* **getLastKey** () +public **setLastKey** (*string* $lastKey) + +Sets the last key used in the cache -Gets the last key stored by the cache +public *string* **getLastKey** () -abstract public **get** () +Gets the last key stored by the cache -... diff --git a/en/api/Phalcon_Cache_BackendInterface.rst b/en/api/Phalcon_Cache_BackendInterface.rst index 27cd13d99555..cb165d33f8ca 100644 --- a/en/api/Phalcon_Cache_BackendInterface.rst +++ b/en/api/Phalcon_Cache_BackendInterface.rst @@ -7,7 +7,7 @@ Phalcon\\Cache\\BackendInterface initializer Methods --------- -abstract public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontendObject, *array* $backendOptions) +abstract public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontend, *array* $options) Phalcon\\Cache\\Backend constructor @@ -31,6 +31,12 @@ Returns front-end instance adapter related to the back-end +abstract public *array* **getOptions** () + +Returns the backend options + + + abstract public *boolean* **isFresh** () Checks whether the last cache is fresh or cached @@ -43,15 +49,45 @@ Checks whether the cache has starting buffering or not +abstract public **setLastKey** (*string* $lastKey) + +Sets the last key used in the cache + + + abstract public *string* **getLastKey** () Gets the last key stored by the cache -abstract public **get** (*unknown* $key) +abstract public *mixed* **get** (*int|string* $keyName, *long* $lifetime) + +Returns a cached content + + + +abstract public **save** (*int|string* $keyName, *string* $content, *long* $lifetime, *boolean* $stopBuffer) + +Stores cached content into the file backend and stops the frontend + + + +abstract public *boolean* **delete** (*int|string* $keyName) + +Deletes a value from the cache by its key + + + +abstract public *array* **queryKeys** (*string* $prefix) + +Query the existing cached keys + + + +abstract public *boolean* **exists** (*string* $keyName, *long* $lifetime) -Returns data from the backend +Checks if cache exists and it hasn't expired diff --git a/en/api/Phalcon_Cache_Backend_Apc.rst b/en/api/Phalcon_Cache_Backend_Apc.rst index 48564198be56..ddf4fe2df12c 100755 --- a/en/api/Phalcon_Cache_Backend_Apc.rst +++ b/en/api/Phalcon_Cache_Backend_Apc.rst @@ -58,13 +58,13 @@ Query the existing cached keys -public *boolean* **exists** (*string* $keyName) +public *boolean* **exists** (*string* $keyName, *long* $lifetime) -Checks if cache exists. +Checks if cache exists and it hasn't expired -public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontendObject, *array* $backendOptions) inherited from Phalcon\\Cache\\Backend +public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontend, *array* $options) inherited from Phalcon\\Cache\\Backend Phalcon\\Cache\\Backend constructor @@ -88,6 +88,12 @@ Returns front-end instance adapter related to the back-end +public *array* **getOptions** () inherited from Phalcon\\Cache\\Backend + +Returns the backend options + + + public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend Checks whether the last cache is fresh or cached @@ -100,6 +106,12 @@ Checks whether the cache has starting buffering or not +public **setLastKey** (*string* $lastKey) inherited from Phalcon\\Cache\\Backend + +Sets the last key used in the cache + + + public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend Gets the last key stored by the cache diff --git a/en/api/Phalcon_Cache_Backend_File.rst b/en/api/Phalcon_Cache_Backend_File.rst index 9ed5d418190f..21dd0633f6ca 100755 --- a/en/api/Phalcon_Cache_Backend_File.rst +++ b/en/api/Phalcon_Cache_Backend_File.rst @@ -36,9 +36,9 @@ Allows to cache output fragments using a file backend Methods --------- -public **__construct** (*mixed* $frontendObject, *array* $backendOptions) +public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontend, *array* $options) -Phalcon\\Backend\\Adapter\\File constructor +Phalcon\\Cache\\Backend\\File constructor @@ -66,9 +66,9 @@ Query the existing cached keys -public *boolean* **exists** (*string* $keyName) +public *boolean* **exists** (*string* $keyName, *long* $lifetime) -Checks if cache exists. +Checks if cache exists and it isn't expired @@ -90,6 +90,12 @@ Returns front-end instance adapter related to the back-end +public *array* **getOptions** () inherited from Phalcon\\Cache\\Backend + +Returns the backend options + + + public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend Checks whether the last cache is fresh or cached @@ -102,6 +108,12 @@ Checks whether the cache has starting buffering or not +public **setLastKey** (*string* $lastKey) inherited from Phalcon\\Cache\\Backend + +Sets the last key used in the cache + + + public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend Gets the last key stored by the cache diff --git a/en/api/Phalcon_Cache_Backend_Memcache.rst b/en/api/Phalcon_Cache_Backend_Memcache.rst index 963fe46f87c5..a28eea5381b7 100755 --- a/en/api/Phalcon_Cache_Backend_Memcache.rst +++ b/en/api/Phalcon_Cache_Backend_Memcache.rst @@ -34,9 +34,9 @@ Allows to cache output fragments, PHP data or raw data to a memcache backend Th Methods --------- -public **__construct** (*mixed* $frontendObject, *array* $backendOptions) +public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontend, *array* $options) -Phalcon\\Backend\\Adapter\\Memcache constructor +Phalcon\\Cache\\Backend\\Memcache constructor @@ -70,9 +70,9 @@ Query the existing cached keys -public *boolean* **exists** (*string* $keyName) +public *boolean* **exists** (*string* $keyName, *long* $lifetime) -Checks if cache exists. +Checks if cache exists and it hasn't expired @@ -100,6 +100,12 @@ Returns front-end instance adapter related to the back-end +public *array* **getOptions** () inherited from Phalcon\\Cache\\Backend + +Returns the backend options + + + public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend Checks whether the last cache is fresh or cached @@ -112,6 +118,12 @@ Checks whether the cache has starting buffering or not +public **setLastKey** (*string* $lastKey) inherited from Phalcon\\Cache\\Backend + +Sets the last key used in the cache + + + public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend Gets the last key stored by the cache diff --git a/en/api/Phalcon_Cache_Backend_Mongo.rst b/en/api/Phalcon_Cache_Backend_Mongo.rst index 2e130f19001e..703d4642b155 100644 --- a/en/api/Phalcon_Cache_Backend_Mongo.rst +++ b/en/api/Phalcon_Cache_Backend_Mongo.rst @@ -34,9 +34,9 @@ Allows to cache output fragments, PHP data or raw data to a MongoDb backend Methods --------- -public **__construct** (*mixed* $frontendObject, *array* $backendOptions) +public **__construct** (:doc:`Phalcon\\Cache\\FrontendInterface ` $frontend, *array* $options) -Phalcon\\Backend\\Adapter\\Mongo constructor +Phalcon\\Cache\\Backend\\Mongo constructor @@ -70,9 +70,9 @@ Query the existing cached keys -public *boolean* **exists** (*string* $keyName) +public *boolean* **exists** (*string* $keyName, *long* $lifetime) -Checks if cache exists. +Checks if cache exists and it hasn't expired @@ -94,6 +94,12 @@ Returns front-end instance adapter related to the back-end +public *array* **getOptions** () inherited from Phalcon\\Cache\\Backend + +Returns the backend options + + + public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend Checks whether the last cache is fresh or cached @@ -106,6 +112,12 @@ Checks whether the cache has starting buffering or not +public **setLastKey** (*string* $lastKey) inherited from Phalcon\\Cache\\Backend + +Sets the last key used in the cache + + + public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend Gets the last key stored by the cache diff --git a/en/api/Phalcon_DI.rst b/en/api/Phalcon_DI.rst index 9361deda824e..e254d0c09fc1 100644 --- a/en/api/Phalcon_DI.rst +++ b/en/api/Phalcon_DI.rst @@ -15,13 +15,13 @@ Phalcon\\DI constructor -public :doc:`Phalcon\\DI ` **set** (*string* $name, *mixed* $config, *boolean* $shared) +public :doc:`Phalcon\\Di\\ServiceInterface ` **set** (*string* $name, *mixed* $config, *boolean* $shared) Registers a service in the services container -public :doc:`Phalcon\\DI ` **setShared** (*string* $name, *mixed* $config) +public :doc:`Phalcon\\Di\\ServiceInterface ` **setShared** (*string* $name, *mixed* $config) Registers an "always shared" service in the services container @@ -33,7 +33,7 @@ Removes a service in the services container -public :doc:`Phalcon\\DI ` **attempt** (*string* $name, *mixed* $config, *unknown* $shared) +public :doc:`Phalcon\\Di\\ServiceInterface ` **attempt** (*string* $name, *mixed* $config, *unknown* $shared) Attempts to register a service in the services container Only is successful if a service hasn't been registered previously with the same name @@ -45,6 +45,12 @@ Returns a service definition without resolving +public :doc:`Phalcon\\Di\\ServiceInterface ` **getService** (*unknown* $name) + +Returns a Phalcon\\Di\\Service instance + + + public *mixed* **get** (*string* $name, *array* $parameters) Resolves the service based on its configuration diff --git a/en/api/Phalcon_DI_FactoryDefault.rst b/en/api/Phalcon_DI_FactoryDefault.rst index 9e1ea43dd4a6..42a17aa901f8 100644 --- a/en/api/Phalcon_DI_FactoryDefault.rst +++ b/en/api/Phalcon_DI_FactoryDefault.rst @@ -17,13 +17,13 @@ Phalcon\\DI\\FactoryDefault constructor -public :doc:`Phalcon\\DI ` **set** (*string* $name, *mixed* $config, *boolean* $shared) inherited from Phalcon\\DI +public :doc:`Phalcon\\Di\\ServiceInterface ` **set** (*string* $name, *mixed* $config, *boolean* $shared) inherited from Phalcon\\DI Registers a service in the services container -public :doc:`Phalcon\\DI ` **setShared** (*string* $name, *mixed* $config) inherited from Phalcon\\DI +public :doc:`Phalcon\\Di\\ServiceInterface ` **setShared** (*string* $name, *mixed* $config) inherited from Phalcon\\DI Registers an "always shared" service in the services container @@ -35,7 +35,7 @@ Removes a service in the services container -public :doc:`Phalcon\\DI ` **attempt** (*string* $name, *mixed* $config, *unknown* $shared) inherited from Phalcon\\DI +public :doc:`Phalcon\\Di\\ServiceInterface ` **attempt** (*string* $name, *mixed* $config, *unknown* $shared) inherited from Phalcon\\DI Attempts to register a service in the services container Only is successful if a service hasn't been registered previously with the same name @@ -47,6 +47,12 @@ Returns a service definition without resolving +public :doc:`Phalcon\\Di\\ServiceInterface ` **getService** (*unknown* $name) inherited from Phalcon\\DI + +Returns a Phalcon\\Di\\Service instance + + + public *mixed* **get** (*string* $name, *array* $parameters) inherited from Phalcon\\DI Resolves the service based on its configuration diff --git a/en/api/Phalcon_DI_FactoryDefault_CLI.rst b/en/api/Phalcon_DI_FactoryDefault_CLI.rst index f43688da3923..87aa4c9eae88 100644 --- a/en/api/Phalcon_DI_FactoryDefault_CLI.rst +++ b/en/api/Phalcon_DI_FactoryDefault_CLI.rst @@ -17,13 +17,13 @@ Phalcon\\DI\\FactoryDefault\\CLI constructor -public :doc:`Phalcon\\DI ` **set** (*string* $name, *mixed* $config, *boolean* $shared) inherited from Phalcon\\DI +public :doc:`Phalcon\\Di\\ServiceInterface ` **set** (*string* $name, *mixed* $config, *boolean* $shared) inherited from Phalcon\\DI Registers a service in the services container -public :doc:`Phalcon\\DI ` **setShared** (*string* $name, *mixed* $config) inherited from Phalcon\\DI +public :doc:`Phalcon\\Di\\ServiceInterface ` **setShared** (*string* $name, *mixed* $config) inherited from Phalcon\\DI Registers an "always shared" service in the services container @@ -35,7 +35,7 @@ Removes a service in the services container -public :doc:`Phalcon\\DI ` **attempt** (*string* $name, *mixed* $config, *unknown* $shared) inherited from Phalcon\\DI +public :doc:`Phalcon\\Di\\ServiceInterface ` **attempt** (*string* $name, *mixed* $config, *unknown* $shared) inherited from Phalcon\\DI Attempts to register a service in the services container Only is successful if a service hasn't been registered previously with the same name @@ -47,6 +47,12 @@ Returns a service definition without resolving +public :doc:`Phalcon\\Di\\ServiceInterface ` **getService** (*unknown* $name) inherited from Phalcon\\DI + +Returns a Phalcon\\Di\\Service instance + + + public *mixed* **get** (*string* $name, *array* $parameters) inherited from Phalcon\\DI Resolves the service based on its configuration diff --git a/en/api/Phalcon_DI_Service.rst b/en/api/Phalcon_DI_Service.rst index 285a0088c491..9fecfa8e8ffe 100644 --- a/en/api/Phalcon_DI_Service.rst +++ b/en/api/Phalcon_DI_Service.rst @@ -1,7 +1,9 @@ Class **Phalcon\\DI\\Service** ============================== -Phalcon\\DI Represents a service in the services container +*implements* :doc:`Phalcon\\DI\\ServiceInterface ` + +Represents individually a service in the services container Methods @@ -25,7 +27,7 @@ Sets if the service is shared or not -public *boolean* **getShared** () +public *boolean* **isShared** () Check whether the service is shared or not diff --git a/en/api/Phalcon_DI_ServiceInterface.rst b/en/api/Phalcon_DI_ServiceInterface.rst new file mode 100644 index 000000000000..de299899256a --- /dev/null +++ b/en/api/Phalcon_DI_ServiceInterface.rst @@ -0,0 +1,57 @@ +Interface **Phalcon\\DI\\ServiceInterface** +=========================================== + +Phalcon\\DI\\ServiceInterface initializer + + +Methods +--------- + +abstract public **__construct** (*string* $name, *mixed* $definition, *boolean* $shared) + +Phalcon\\DI\\Service + + + +abstract public **getName** () + +Returns the service's name + + + +abstract public **setShared** (*boolean* $shared) + +Sets if the service is shared or not + + + +abstract public *boolean* **isShared** () + +Check whether the service is shared or not + + + +abstract public **setDefinition** (*mixed* $definition) + +Set the service definition + + + +abstract public *mixed* **getDefinition** () + +Returns the service definition + + + +abstract public *mixed* **resolve** (*unknown* $parameters) + +Resolves the service + + + +abstract public static :doc:`Phalcon\\DI\\Service ` **__set_state** (*array* $attributes) + +Restore the interal state of a service + + + diff --git a/en/api/Phalcon_Db_Adapter.rst b/en/api/Phalcon_Db_Adapter.rst index df4f1c338e35..4bbd00b0ba50 100644 --- a/en/api/Phalcon_Db_Adapter.rst +++ b/en/api/Phalcon_Db_Adapter.rst @@ -27,7 +27,7 @@ Returns the internal event manager -public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) Returns the first row in a SQL query result @@ -46,7 +46,7 @@ Returns the first row in a SQL query result -public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) Dumps the complete result of a query into an array diff --git a/en/api/Phalcon_Db_Adapter_Pdo.rst b/en/api/Phalcon_Db_Adapter_Pdo.rst index f140b0d3c16d..723453824919 100644 --- a/en/api/Phalcon_Db_Adapter_Pdo.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo.rst @@ -36,7 +36,7 @@ This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Ca -protected *\PDOStatement* **_executePrepared** () +public *\PDOStatement* **executePrepared** (*\PDOStatement* $statement, *array* $placeholders, *array* $dataTypes) Executes a prepared statement binding @@ -193,7 +193,7 @@ Returns the internal event manager -public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Returns the first row in a SQL query result @@ -212,7 +212,7 @@ Returns the first row in a SQL query result -public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Dumps the complete result of a query into an array diff --git a/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst index 6928ef19e1ad..71348b2bb54e 100755 --- a/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -57,7 +57,7 @@ This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Ca -protected *\PDOStatement* **_executePrepared** () inherited from Phalcon\\Db\\Adapter\\Pdo +public *\PDOStatement* **executePrepared** (*\PDOStatement* $statement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo Executes a prepared statement binding @@ -208,7 +208,7 @@ Returns the internal event manager -public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Returns the first row in a SQL query result @@ -227,7 +227,7 @@ Returns the first row in a SQL query result -public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Dumps the complete result of a query into an array diff --git a/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst index c71e70639d3e..62d34cde32aa 100755 --- a/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -55,7 +55,7 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo -protected *\PDOStatement* **_executePrepared** () inherited from Phalcon\\Db\\Adapter\\Pdo +public *\PDOStatement* **executePrepared** (*\PDOStatement* $statement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo Executes a prepared statement binding @@ -200,7 +200,7 @@ Returns the internal event manager -public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Returns the first row in a SQL query result @@ -219,7 +219,7 @@ Returns the first row in a SQL query result -public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Dumps the complete result of a query into an array diff --git a/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst index abe4550a630f..255d003af4a7 100644 --- a/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst +++ b/en/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -59,7 +59,7 @@ Constructor for Phalcon\\Db\\Adapter\\Pdo -protected *\PDOStatement* **_executePrepared** () inherited from Phalcon\\Db\\Adapter\\Pdo +public *\PDOStatement* **executePrepared** (*\PDOStatement* $statement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo Executes a prepared statement binding @@ -204,7 +204,7 @@ Returns the internal event manager -public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Returns the first row in a SQL query result @@ -223,7 +223,7 @@ Returns the first row in a SQL query result -public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $placeholders) inherited from Phalcon\\Db\\Adapter +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode, *array* $bindParams, *array* $bindTypes) inherited from Phalcon\\Db\\Adapter Dumps the complete result of a query into an array diff --git a/en/api/Phalcon_Db_Dialect.rst b/en/api/Phalcon_Db_Dialect.rst index 1b18c9856fc3..606ff390973b 100644 --- a/en/api/Phalcon_Db_Dialect.rst +++ b/en/api/Phalcon_Db_Dialect.rst @@ -31,13 +31,13 @@ Gets a list of columns -protected *string* **_getSqlExpression** () +public *string* **getSqlExpression** (*array* $expression, *string* $escapeChar) Transform an intermediate representation for a expression into a database system valid expression -protected *string* **_getSqlTable** () +public *string* **getSqlTable** (*unknown* $table, *string* $escapeChar) Transform an intermediate representation for a schema/table into a database system valid expression diff --git a/en/api/Phalcon_Db_Dialect_Mysql.rst b/en/api/Phalcon_Db_Dialect_Mysql.rst index 9583a8f51cac..242cfe35a840 100755 --- a/en/api/Phalcon_Db_Dialect_Mysql.rst +++ b/en/api/Phalcon_Db_Dialect_Mysql.rst @@ -149,13 +149,13 @@ Gets a list of columns -protected *string* **_getSqlExpression** () inherited from Phalcon\\Db\\Dialect +public *string* **getSqlExpression** (*array* $expression, *string* $escapeChar) inherited from Phalcon\\Db\\Dialect Transform an intermediate representation for a expression into a database system valid expression -protected *string* **_getSqlTable** () inherited from Phalcon\\Db\\Dialect +public *string* **getSqlTable** (*unknown* $table, *string* $escapeChar) inherited from Phalcon\\Db\\Dialect Transform an intermediate representation for a schema/table into a database system valid expression diff --git a/en/api/Phalcon_Db_Dialect_Postgresql.rst b/en/api/Phalcon_Db_Dialect_Postgresql.rst index 46f6cbd8f536..316e2568ccf2 100755 --- a/en/api/Phalcon_Db_Dialect_Postgresql.rst +++ b/en/api/Phalcon_Db_Dialect_Postgresql.rst @@ -149,13 +149,13 @@ Gets a list of columns -protected *string* **_getSqlExpression** () inherited from Phalcon\\Db\\Dialect +public *string* **getSqlExpression** (*array* $expression, *string* $escapeChar) inherited from Phalcon\\Db\\Dialect Transform an intermediate representation for a expression into a database system valid expression -protected *string* **_getSqlTable** () inherited from Phalcon\\Db\\Dialect +public *string* **getSqlTable** (*unknown* $table, *string* $escapeChar) inherited from Phalcon\\Db\\Dialect Transform an intermediate representation for a schema/table into a database system valid expression diff --git a/en/api/Phalcon_Db_Dialect_Sqlite.rst b/en/api/Phalcon_Db_Dialect_Sqlite.rst index 7af41349d6dc..ea7b2847601c 100644 --- a/en/api/Phalcon_Db_Dialect_Sqlite.rst +++ b/en/api/Phalcon_Db_Dialect_Sqlite.rst @@ -155,13 +155,13 @@ Gets a list of columns -protected *string* **_getSqlExpression** () inherited from Phalcon\\Db\\Dialect +public *string* **getSqlExpression** (*array* $expression, *string* $escapeChar) inherited from Phalcon\\Db\\Dialect Transform an intermediate representation for a expression into a database system valid expression -protected *string* **_getSqlTable** () inherited from Phalcon\\Db\\Dialect +public *string* **getSqlTable** (*unknown* $table, *string* $escapeChar) inherited from Phalcon\\Db\\Dialect Transform an intermediate representation for a schema/table into a database system valid expression diff --git a/en/api/Phalcon_DiInterface.rst b/en/api/Phalcon_DiInterface.rst index 1f903fa8568b..5fff2ba1403c 100644 --- a/en/api/Phalcon_DiInterface.rst +++ b/en/api/Phalcon_DiInterface.rst @@ -7,13 +7,13 @@ Phalcon\\DiInterface initializer Methods --------- -abstract public :doc:`Phalcon\\DI ` **set** (*string* $alias, *mixed* $config, *boolean* $shared) +abstract public :doc:`Phalcon\\Di\\ServiceInterface ` **set** (*string* $alias, *mixed* $config, *boolean* $shared) Registers a service in the services container -abstract public :doc:`Phalcon\\DI ` **setShared** (*string* $name, *mixed* $config) +abstract public :doc:`Phalcon\\Di\\ServiceInterface ` **setShared** (*string* $name, *mixed* $config) Registers an "always shared" service in the services container @@ -25,7 +25,7 @@ Removes a service in the services container -abstract public :doc:`Phalcon\\DiInterface ` **attempt** (*string* $alias, *mixed* $config, *boolean* $shared) +abstract public :doc:`Phalcon\\Di\\ServiceInterface ` **attempt** (*string* $alias, *mixed* $config, *boolean* $shared) Attempts to register a service in the services container Only is successful if a service hasn't been registered previously with the same name @@ -49,6 +49,12 @@ Returns a service definition without resolving +abstract public :doc:`Phalcon\\Di\\ServiceInterface ` **getService** (*unknown* $name) + +Returns the corresponding Phalcon\\Di\\Service instance for a service + + + abstract public *boolean* **has** (*string* $alias) Check whether the DI contains a service by a name diff --git a/en/api/Phalcon_Dispatcher.rst b/en/api/Phalcon_Dispatcher.rst index 0b94d8026b3f..d360e0fb710e 100644 --- a/en/api/Phalcon_Dispatcher.rst +++ b/en/api/Phalcon_Dispatcher.rst @@ -60,6 +60,18 @@ Sets the default action suffix +public **setNamespaceName** (*string* $namespaceName) + +Sets a namespace to be prepended to the handler name + + + +public *string* **getNamespaceName** () + +Gets a namespace to be prepended to the current handler name + + + public **setDefaultNamespace** (*string* $namespace) Sets the default namespace @@ -108,7 +120,7 @@ Set a param by its name or numeric index -public *mixed* **getParam** (*mixed* $param, *string|array* $filters) +public *mixed* **getParam** (*mixed* $param, *string|array* $filters, *mixed* $defaultValue) Gets a param by its name or numeric index diff --git a/en/api/Phalcon_Http_Cookie.rst b/en/api/Phalcon_Http_Cookie.rst index 6aec67d0a8d0..78e27c4161a6 100644 --- a/en/api/Phalcon_Http_Cookie.rst +++ b/en/api/Phalcon_Http_Cookie.rst @@ -3,13 +3,13 @@ Class **Phalcon\\Http\\Cookie** *implements* :doc:`Phalcon\\DI\\InjectionAwareInterface ` -Provide OO wrappers to +Provide OO wrappers to manage a HTTP cookie Methods --------- -public **__construct** (*unknown* $name, *unknown* $value, *unknown* $expire, *unknown* $path) +public **__construct** (*string* $name, *mixed* $value, *int* $expire, *string* $path) Phalcon\\Http\\Cookie constructor @@ -27,24 +27,51 @@ Returns the internal dependency injector -public **get** () +public :doc:`Phalcon\\Http\\CookieInterface ` **setValue** (*string* $value) -... +Sets the cookie's value -public :doc:`Phalcon\\Http\\CookieInterface ` **setValue** (*string* $value) -Sets the cookie's value +public *mixed* **getValue** (*unknown* $filters, *unknown* $defaultValue) + +Returns the cookie's value + + + +public :doc:`Phalcon\\Http\\Cookie ` **setExpiration** (*int* $expire) + +Sets the cookie's expiration time + + + +public *string* **getExpiration** () + +Returns the current expiration time + + + +public :doc:`Phalcon\\Http\\Cookie ` **setPath** (*unknown* $path) + +Sets the cookie's expiration time + + + +public *string* **getPath** () + +Returns the current cookie's path + + +public :doc:`Phalcon\\Http\\Cookie ` **setSecure** (*boolean* $secure) +Sets if the cookie must only be sent when the connection is secure (HTTPS) -public **setExpiration** (*unknown* $expire) -... +public *boolean* **getSecure** () -public **getValue** () +Returns whether the cookie must only be sent when the connection is secure (HTTPS) -... diff --git a/en/api/Phalcon_Http_Cookie_Exception.rst b/en/api/Phalcon_Http_Cookie_Exception.rst new file mode 100644 index 000000000000..06ce7ef111e2 --- /dev/null +++ b/en/api/Phalcon_Http_Cookie_Exception.rst @@ -0,0 +1,68 @@ +Class **Phalcon\\Http\\Cookie\\Exception** +========================================== + +*extends* :doc:`Phalcon\\Exception ` + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/en/api/Phalcon_Http_Response.rst b/en/api/Phalcon_Http_Response.rst index 4a2afb251cf8..f716742ff6e7 100755 --- a/en/api/Phalcon_Http_Response.rst +++ b/en/api/Phalcon_Http_Response.rst @@ -44,12 +44,30 @@ Sets the HTTP response code -public :doc:`Phalcon\\Http\\Response\\Headers ` **getHeaders** () +public :doc:`Phalcon\\Http\\ResponseInterface ` **setHeaders** (:doc:`Phalcon\\Http\\Response\\HeadersInterface ` $headers) + +Sets a headers bag for the response externally + + + +public :doc:`Phalcon\\Http\\Response\\HeadersInterface ` **getHeaders** () Returns headers set by the user +public :doc:`Phalcon\\Http\\ResponseInterface ` **setCookies** (:doc:`Phalcon\\Http\\Response\\CookiesInterface ` $cookies) + +Sets a cookies bag for the response externally + + + +public :doc:`Phalcon\\Http\\Response\\CookiesInterface ` **getCookies** () + +Returns coookies set by the user + + + public :doc:`Phalcon\\Http\\ResponseInterface ` **setHeader** (*string* $name, *string* $value) Overwrites a header in the response @@ -116,6 +134,7 @@ Redirect by HTTP to another action or URL redirect("posts/index"); $response->redirect("http://en.wikipedia.org", true); $response->redirect("http://www.example.com/new-location", true, 301); @@ -148,6 +167,12 @@ Gets the HTTP response body +public *boolean* **isSent** () + +Check if the response is already sent + + + public :doc:`Phalcon\\Http\\ResponseInterface ` **sendHeaders** () Sends headers to the client diff --git a/en/api/Phalcon_Http_Response_Cookies.rst b/en/api/Phalcon_Http_Response_Cookies.rst index 4f190698f048..7e95d42a7b03 100644 --- a/en/api/Phalcon_Http_Response_Cookies.rst +++ b/en/api/Phalcon_Http_Response_Cookies.rst @@ -1,7 +1,9 @@ Class **Phalcon\\Http\\Response\\Cookies** ========================================== -Phalcon\\Http\\Response\\Headers This class is a bag to manage the response headers +*implements* :doc:`Phalcon\\DI\\InjectionAwareInterface ` + +This class is a bag to manage the cookies Methods @@ -13,15 +15,27 @@ Phalcon\\Http\\Response\\Cookies constructor -public **set** () +public **setDI** (:doc:`Phalcon\\DiInterface ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DiInterface ` **getDI** () + +Returns the internal dependency injector + + + +public **set** (*string* $name, *mixed* $value, *int* $expire, *string* $path) Sets a header to be sent at the end of the request -public *string* **get** () +public :doc:`Phalcon\\Http\\Cookie ` **get** (*string* $name) -Gets a header value from the internal bag +Gets a cookie from the bag diff --git a/en/api/Phalcon_Http_Response_Headers.rst b/en/api/Phalcon_Http_Response_Headers.rst index 8e2b3540393c..bebdebdad014 100755 --- a/en/api/Phalcon_Http_Response_Headers.rst +++ b/en/api/Phalcon_Http_Response_Headers.rst @@ -1,6 +1,8 @@ Class **Phalcon\\Http\\Response\\Headers** ========================================== +*implements* :doc:`Phalcon\\Http\\Response\\HeadersInterface ` + This class is a bag to manage the response headers diff --git a/en/api/Phalcon_Http_Response_HeadersInterface.rst b/en/api/Phalcon_Http_Response_HeadersInterface.rst new file mode 100644 index 000000000000..dabc036cc81f --- /dev/null +++ b/en/api/Phalcon_Http_Response_HeadersInterface.rst @@ -0,0 +1,45 @@ +Interface **Phalcon\\Http\\Response\\HeadersInterface** +======================================================= + +Phalcon\\Http\\Response\\HeadersInterface initializer + + +Methods +--------- + +abstract public **set** (*string* $name, *string* $value) + +Sets a header to be sent at the end of the request + + + +abstract public *string* **get** (*string* $name) + +Gets a header value from the internal bag + + + +abstract public **setRaw** (*string* $header) + +Sets a raw header to be sent at the end of the request + + + +abstract public *boolean* **send** () + +Sends the headers to the client + + + +abstract public **reset** () + +Reset set headers + + + +abstract public static :doc:`Phalcon\\Http\\Response\\HeadersInterface ` **__set_state** (*unknown* $data) + +Restore a Phalcon\\Http\\Response\\Headers object + + + diff --git a/en/api/Phalcon_Mvc_Dispatcher.rst b/en/api/Phalcon_Mvc_Dispatcher.rst index 4c539a233c12..7d28ab692c15 100644 --- a/en/api/Phalcon_Mvc_Dispatcher.rst +++ b/en/api/Phalcon_Mvc_Dispatcher.rst @@ -121,6 +121,18 @@ Sets the default action suffix +public **setNamespaceName** (*string* $namespaceName) inherited from Phalcon\\Dispatcher + +Sets a namespace to be prepended to the handler name + + + +public *string* **getNamespaceName** () inherited from Phalcon\\Dispatcher + +Gets a namespace to be prepended to the current handler name + + + public **setDefaultNamespace** (*string* $namespace) inherited from Phalcon\\Dispatcher Sets the default namespace @@ -169,7 +181,7 @@ Set a param by its name or numeric index -public *mixed* **getParam** (*mixed* $param, *string|array* $filters) inherited from Phalcon\\Dispatcher +public *mixed* **getParam** (*mixed* $param, *string|array* $filters, *mixed* $defaultValue) inherited from Phalcon\\Dispatcher Gets a param by its name or numeric index diff --git a/en/api/Phalcon_Mvc_Model.rst b/en/api/Phalcon_Mvc_Model.rst index c28bb5ad8e97..1d1a28a17c2d 100755 --- a/en/api/Phalcon_Mvc_Model.rst +++ b/en/api/Phalcon_Mvc_Model.rst @@ -568,7 +568,7 @@ Inserts a model instance. If the instance already exists in the persistance it w public *boolean* **update** (*array* $data) -Updates a model instance. If the instance doesn't exists in the persistance it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistance it will throw an exception Returning true on success or false otherwise. .. code-block:: php @@ -577,7 +577,7 @@ Updates a model instance. If the instance doesn't exists in the persistance it w //Updating a robot name $robot = Robots::findFirst("id=100"); $robot->name = "Biomass"; - $robot->save(); + $robot->update(); diff --git a/en/api/Phalcon_Mvc_ModelInterface.rst b/en/api/Phalcon_Mvc_ModelInterface.rst index 9564e4b5acaa..891bdb4fe3aa 100644 --- a/en/api/Phalcon_Mvc_ModelInterface.rst +++ b/en/api/Phalcon_Mvc_ModelInterface.rst @@ -135,7 +135,7 @@ Inserts a model instance. If the instance already exists in the persistance it w abstract public *boolean* **update** (*array* $data) -Updates a model instance. If the instance doesn't exists in the persistance it will throw an exception Returning true on success or false otherwise. +Updates a model instance. If the instance doesn't exist in the persistance it will throw an exception Returning true on success or false otherwise. diff --git a/en/api/Phalcon_Mvc_Model_Manager.rst b/en/api/Phalcon_Mvc_Model_Manager.rst index daf555e6f414..10a7ce339d1d 100755 --- a/en/api/Phalcon_Mvc_Model_Manager.rst +++ b/en/api/Phalcon_Mvc_Model_Manager.rst @@ -162,7 +162,7 @@ Gets hasOne relations defined on a model public *array* **getRelations** (*string* $first, *string* $second) -Query the relations between two models +Query the relationships between two models @@ -178,3 +178,9 @@ Creates a Phalcon\\Mvc\\Model\\Query and execute it +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **createBuilder** (*string* $params) + +Creates a Phalcon\\Mvc\\Model\\Query\\Builder + + + diff --git a/en/api/Phalcon_Mvc_Model_MetaData_Files.rst b/en/api/Phalcon_Mvc_Model_MetaData_Files.rst index 146b5e56720c..0e0544a20ccf 100644 --- a/en/api/Phalcon_Mvc_Model_MetaData_Files.rst +++ b/en/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -59,13 +59,13 @@ Phalcon\\Mvc\\Model\\MetaData\\Files constructor public *array* **read** (*unknown* $key) -Reads meta-data from $_SESSION +Reads meta-data from files public **write** (*string* $key, *array* $data) -Writes the meta-data to $_SESSION +Writes the meta-data to files diff --git a/en/api/Phalcon_Mvc_Model_Query.rst b/en/api/Phalcon_Mvc_Model_Query.rst index 2bd68caae233..913e0d423713 100755 --- a/en/api/Phalcon_Mvc_Model_Query.rst +++ b/en/api/Phalcon_Mvc_Model_Query.rst @@ -23,6 +23,17 @@ This class takes a PHQL intermediate representation and executes it. +Constants +--------- + +*integer* **TYPE_SELECT** + +*integer* **TYPE_INSERT** + +*integer* **TYPE_UPDATE** + +*integer* **TYPE_DELETE** + Methods --------- @@ -98,12 +109,6 @@ Resolves all the JOINS in a SELECT statement -protected *string* **_getLimitClause** () - -Returns a processed limit clause for a SELECT statement - - - protected *string* **_getOrderClause** () Returns a processed order clause for a SELECT statement @@ -146,9 +151,22 @@ Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang genera -public **setCache** () +public **cache** (*array* $cacheOptions) + +Sets the cache parameters of the query + + + +public **getCacheOptions** () + +Returns the current cache options + + + +public :doc:`Phalcon\\Cache\\BackendInterface ` **getCache** () + +Returns the current cache backend instance -... protected :doc:`Phalcon\\Mvc\\Model\\ResultsetInterface ` **_executeSelect** () @@ -163,6 +181,12 @@ Executes the INSERT intermediate representation producing a Phalcon\\Mvc\\Model\ +protected :doc:`Phalcon\\Mvc\\Model\\ResultsetInterface ` **_getRelatedRecords** () + +Query the records on which the UPDATE/DELETE operation well be done + + + protected :doc:`Phalcon\\Mvc\\Model\\Query\\StatusInterface ` **_executeUpdate** () Executes the UPDATE intermediate representation producing a Phalcon\\Mvc\\Model\\Query\\Status @@ -181,3 +205,27 @@ Executes a parsed PHQL statement +public **setType** (*int* $type) + +Sets the type of PHQL statement to be executed + + + +public *int* **getType** () + +Gets the type of PHQL statement executed + + + +public **setIntermediate** (*array* $intermediate) + +Allows to set the IR to be executed + + + +public *array* **getIntermediate** () + +Returns the intermediate representation of the PHQL statement + + + diff --git a/en/api/Phalcon_Mvc_Model_Query_Builder.rst b/en/api/Phalcon_Mvc_Model_Query_Builder.rst index c6aba82b5d11..9c53fdd80baa 100644 --- a/en/api/Phalcon_Mvc_Model_Query_Builder.rst +++ b/en/api/Phalcon_Mvc_Model_Query_Builder.rst @@ -20,7 +20,7 @@ public **__construct** (*array* $params) -public **setDI** (:doc:`Phalcon\\DiInterface ` $dependencyInjector) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setDI** (:doc:`Phalcon\\DiInterface ` $dependencyInjector) Sets the DependencyInjector container @@ -32,7 +32,7 @@ Returns the DependencyInjector container -public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setColumns** (*string|array* $columns) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **columns** (*string|array* $columns) Sets the columns to be queried @@ -44,31 +44,55 @@ Return the columns to be queried -public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setModels** (*string|array* $models) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **from** (*string|array* $models) Sets the models who makes part of the query -public *string|array* **getModels** () +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **addFrom** (*string* $model, *string* $alias) + +Add a model to take part of the query + + + +public *string|array* **getFrom** () Return the models who makes part of the query -public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setConditions** (*int* $conditions) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **join** (*string* $model, *string* $conditions, *string* $alias) + +Sets the models who makes part of the query + + + +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **where** (*string* $conditions) Sets conditions for the query -public *string|array* **getConditions** () +public *string|array* **getWhere** () Return the conditions for the query -public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setHaving** (*int* $having) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **orderBy** (*string* $orderBy) + +Sets a ORDER BY condition clause + + + +public *string|array* **getOrderBy** () + +Return the set ORDER BY clause + + + +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **having** (*string* $having) Sets a HAVING condition clause @@ -80,7 +104,7 @@ Return the columns to be queried -public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setLimit** (*int* $limit, *int* $offset) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **limit** (*int* $limit, *int* $offset) Sets a LIMIT clause @@ -92,13 +116,13 @@ Returns the current LIMIT clause -public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **setGroup** (*string* $group) +public :doc:`Phalcon\\Mvc\\Model\\Query\\Builder ` **groupBy** (*string* $group) Sets a LIMIT clause -public *string* **getGroup** () +public *string* **getGroupBy** () Returns the GROUP BY clause diff --git a/en/api/Phalcon_Mvc_Router.rst b/en/api/Phalcon_Mvc_Router.rst index 77f440edf1eb..bb43c1f81035 100755 --- a/en/api/Phalcon_Mvc_Router.rst +++ b/en/api/Phalcon_Mvc_Router.rst @@ -42,6 +42,12 @@ Get rewrite info +public **setDefaultNamespace** (*string* $namespaceName) + +Sets the name of the default namespace + + + public **setDefaultModule** (*string* $moduleName) Sets the name of the default module @@ -120,6 +126,12 @@ Removes all the pre-defined routes +public *string* **getNamespaceName** () + +Returns processed namespace name + + + public *string* **getModuleName** () Returns processed module name diff --git a/en/api/Phalcon_Mvc_Router_Route.rst b/en/api/Phalcon_Mvc_Router_Route.rst index 9b4689a9e81f..a72129512e46 100644 --- a/en/api/Phalcon_Mvc_Router_Route.rst +++ b/en/api/Phalcon_Mvc_Router_Route.rst @@ -65,7 +65,7 @@ Returns the route's pattern public *string* **getCompiledPattern** () -Returns the route's pattern +Returns the route's compiled pattern @@ -75,6 +75,12 @@ Returns the paths +public *array* **getReversedPaths** () + +Returns the paths using positions as keys and names as values + + + public *string|array* **getHttpMethods** () Returns the HTTP methods that constraint matching the route diff --git a/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst index 0cb4a278f977..e8479c5a79e9 100644 --- a/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst +++ b/en/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -7,29 +7,31 @@ This class reads and compiles volt templates into PHP plain code Methods --------- -public **setDI** (*unknown* $di) +public **setDI** (:doc:`Phalcon\\DiInterface ` $dependencyInjector) -... +Sets the dependency injector -public **getDI** () -... +public :doc:`Phalcon\\DiInterface ` **getDI** () +Returns the internal dependency injector -protected **_functionCall** () + + +protected *string* **_functionCall** () Resolves function intermediate code into PHP function calls -protected **_filter** () +protected *string* **_filter** () Resolves filter intermediate code into PHP function calls -public **_expression** (*array* $expr, *bool* $extendsMode, *bool* $prependDollar) +public *string* **_expression** (*array* $expr, *bool* $extendsMode, *bool* $prependDollar) Resolves an expression node in an AST volt tree diff --git a/en/api/index.rst b/en/api/index.rst index 32cd8dfc68aa..4054e249dc69 100755 --- a/en/api/index.rst +++ b/en/api/index.rst @@ -67,6 +67,7 @@ API Indice Phalcon_Flash_Exception Phalcon_Flash_Session Phalcon_Http_Cookie + Phalcon_Http_Cookie_Exception Phalcon_Http_Request Phalcon_Http_Request_Exception Phalcon_Http_Request_File @@ -159,6 +160,7 @@ API Indice Phalcon_Cache_BackendInterface Phalcon_Cache_FrontendInterface Phalcon_DI_InjectionAwareInterface + Phalcon_DI_ServiceInterface Phalcon_Db_AdapterInterface Phalcon_Db_ColumnInterface Phalcon_Db_DialectInterface @@ -175,6 +177,7 @@ API Indice Phalcon_Http_RequestInterface Phalcon_Http_Request_FileInterface Phalcon_Http_ResponseInterface + Phalcon_Http_Response_HeadersInterface Phalcon_Logger_AdapterInterface Phalcon_Mvc_ControllerInterface Phalcon_Mvc_DispatcherInterface diff --git a/en/reference/acl.rst b/en/reference/acl.rst index 9e52a13775f9..48978798bcd8 100755 --- a/en/reference/acl.rst +++ b/en/reference/acl.rst @@ -172,5 +172,8 @@ The following example demonstrates how to attach listeners to this component: //Bind the eventsManager to the acl component $acl->setEventsManager($eventManagers); +Implementing your own adapters +------------------------------ +The :doc:`Phalcon\\Acl\\AdapterInterface <../api/Phalcon_Acl_AdapterInterface>` interface must be implemented in order to create your own ACL adapters or extend the existing ones. .. _Access Control Lists: http://en.wikipedia.org/wiki/Access_control_list diff --git a/en/reference/apache.rst b/en/reference/apache.rst new file mode 100644 index 000000000000..2903db6f3000 --- /dev/null +++ b/en/reference/apache.rst @@ -0,0 +1,97 @@ +Apache Installation Notes +========================= +Apache_ is a popular and well known web server available on many platforms. + +Configuring Apache for Phalcon +------------------------------ +The following are potential configurations you can use to setup Apache with Phalcon. These notes are primarily +focused on the configuration of the mod-rewrite module allowing to use friendly urls and the +:doc:`router component `. Commonly an application has the following structure: + +.. code-block:: php + + test/ + app/ + controllers/ + models/ + views/ + public/ + css/ + img/ + js/ + index.php + +Directory under the main Document Root +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +This being the most common case, the application is installed in any directory under the document root. +In this case, we use .htaccess 2 files, the first one to hide the application code and forward all requests +to the application document root (public/). + +.. code-block:: apacheconf + + # test/.htaccess + + + RewriteEngine on + RewriteRule ^$ public/ [L] + RewriteRule (.*) public/$1 [L] + + +Now a second .htaccess file is located in the public/ directory, this re-writes all the URIs to the public/index.php file: + +.. code-block:: apacheconf + + # test/public/.htaccess + + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + + +If you do not want to use .htaccess files you can move these configurations to the apache's main configuration file: + +.. code-block:: apacheconf + + + + + RewriteEngine on + RewriteRule ^$ public/ [L] + RewriteRule (.*) public/$1 [L] + + + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + + + + +Virtual Hosts +^^^^^^^^^^^^^ +And this second configuration allow you to install a Phalcon application in a virtual host: + +.. code-block:: apacheconf + + + + ServerAdmin admin@example.host + DocumentRoot "/var/vhosts/test/public" + DirectoryIndex index.php + ServerName example.host + ServerAlias www.example.host + + + Options All + AllowOverride All + Allow from all + + + + + +.. _Apache: http://httpd.apache.org/ diff --git a/en/reference/applications.rst b/en/reference/applications.rst index 6f1f789ed2dd..2f5bfa0e78e4 100644 --- a/en/reference/applications.rst +++ b/en/reference/applications.rst @@ -132,7 +132,9 @@ Each directory in apps/ have its own MVC structure. A Module.php is present to c namespace Multiple\Backend; - class Module + use Phalcon\Mvc\ModuleDefinitionInterface; + + class Module implements ModuleDefinitionInterface { /** @@ -212,7 +214,6 @@ A special bootstrap file is required to load the a multi-module MVC architecture $router->add( "/products/:action", array( - 'module' => 'frontend', 'controller' => 'products', 'action' => 1, ) @@ -249,6 +250,34 @@ A special bootstrap file is required to load the a multi-module MVC architecture echo $e->getMessage(); } +If you want to maintain the module configuration in the bootstrap file you can use an anonymous function to register the +module: + +.. code-block:: php + + registerModules( + array( + 'frontend' => function($di) use ($view) { + $di->setShared('view', function() use ($view) { + $view->setViewsDir('../apps/frontend/views/'); + return $view; + }); + }, + 'backend' => function($di) use ($view) { + $di->setShared('view', function() use ($view) { + $view->setViewsDir('../apps/frontend/views/'); + return $view; + }); + } + ) + ); + When :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>` have modules registered, always is necessary that every matched route returns a valid module. Each registered module has an associated class that offers functions to set the module itself up. Each module class definition must implement two @@ -295,13 +324,13 @@ If you do not wish to use :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Ap getShared('router'); + // Request the services from the services container + $router = $di->get('router'); $router->handle(); $view = $di->getShared('view'); - $dispatcher = $di->getShared('dispatcher'); + $dispatcher = $di->get('dispatcher'); // Pass the proccessed router parameters to the dispatcher $dispatcher->setControllerName($router->getControllerName()); @@ -324,7 +353,7 @@ If you do not wish to use :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Ap // Finish the view $view->finish(); - $response = $di->getShared('response'); + $response = $di->get('response'); // Pass the output of the view to the response $response->setContent($view->getContent()); @@ -372,3 +401,8 @@ The following example demonstrates how to attach listeners to this component: // ... } ); + +External Resources +------------------ + +* `MVC examples on Github `_ diff --git a/en/reference/cache.rst b/en/reference/cache.rst index 2ef32f4e61cf..6be8eba09bf6 100755 --- a/en/reference/cache.rst +++ b/en/reference/cache.rst @@ -245,6 +245,10 @@ The available frontend adapters that are used as interfaces or input sources to | None | It's used to cache any kind of PHP data without serializing them. | :doc:`Phalcon\\Cache\\Frontend\\Data <../api/Phalcon_Cache_Frontend_None>` | +---------+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+ +Implementing your own Frontend adapters +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The :doc:`Phalcon\\Cache\\FrontendInterface <../api/Phalcon_Cache_FrontendInterface>` interface must be implemented in order to create your own frontend adapters or extend the existing ones. + Backend Adapters ---------------- The backend adapters available to store cache data are: @@ -261,6 +265,10 @@ The backend adapters available to store cache data are: | Mongo | Stores data to Mongo Database | MongoDb_ | `Mongo`_ | :doc:`Phalcon\\Cache\\Backend\\Mongo <../api/Phalcon_Cache_Backend_Mongo>` | +-----------+------------------------------------------------+------------+---------------------+-----------------------------------------------------------------------------------+ +Implementing your own Backend adapters +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The :doc:`Phalcon\\Cache\\BackendInterface <../api/Phalcon_Cache_BackendInterface>` interface must be implemented in order to create your own backend adapters or extend the existing ones. + File Backend Options ^^^^^^^^^^^^^^^^^^^^ This backend will store cached content into files in the local server. The available options for this backend are: @@ -303,6 +311,7 @@ This backend will store cached content on a MongoDB server. The available option | collection | Mongo collection in the database | +------------+---------------------------------------------+ + .. _Memcached: http://php.net/manual/en/book.apc.php .. _memcache: http://pecl.php.net/package/memcache .. _APC: http://php.net/manual/en/book.apc.php diff --git a/en/reference/controllers.rst b/en/reference/controllers.rst index 7507c6166164..b2f45057985b 100755 --- a/en/reference/controllers.rst +++ b/en/reference/controllers.rst @@ -63,7 +63,10 @@ The dispatch loop will be executed within the Dispatcher until there are no acti $this->flash->error("You don't have permission to access this area"); // Forward flow to another action - $this->dispatcher->forward(array("controller" => "users", "action" => "signin")); + $this->dispatcher->forward(array( + "controller" => "users", + "action" => "signin" + )); } } @@ -125,7 +128,7 @@ action is executed on a controller. The use of the "__construct" method is not r Injecting Services ------------------ -If a controller extends :doc:`Phalcon\\Mvc\\Controller <../api/Phalcon_Mvc_Controller>` then it have easy access to the service +If a controller extends :doc:`Phalcon\\Mvc\\Controller <../api/Phalcon_Mvc_Controller>` then it has easy access to the service container in application. For example, if we have registered a service like this: .. code-block:: php @@ -136,7 +139,7 @@ container in application. For example, if we have registered a service like this $di->set('storage', function(){ return new Storage('/some/directory'); - }); + }, true); Then, we can access to that service by this way: @@ -156,8 +159,11 @@ Then, we can access to that service by this way: //Accessing the service from the DI $this->di->get('storage')->save('/some/file'); - //Another way to access the service + //Another way to access the service using the magic getter $this->di->getStorage()->save('/some/file'); + + //Another way to access the service using the magic getter + $this->getDi()->getStorage()->save('/some/file'); } } @@ -307,4 +313,33 @@ Any other controller now inherits from ControllerBase, automatically gaining acc } +Events in Controllers +--------------------- +Controllers automatically act as listeners for :doc:`dispatcher ` events, implementing methods with those event names allow +you to implement hook points before/after the actions are executed: + +.. code-block:: php + + getActionName() == 'save') { + $this->flash->error("You don't have permission to save posts"); + return false; + } + } + + public function afterExecuteRoute($dispatcher) + { + // Executed after every found action + } + + } + .. _DRY: http://en.wikipedia.org/wiki/Don't_repeat_yourself diff --git a/en/reference/db.rst b/en/reference/db.rst index a345fcdf2488..71e5e50b2a1c 100755 --- a/en/reference/db.rst +++ b/en/reference/db.rst @@ -21,6 +21,10 @@ This component makes use of adapters to encapsulate specific database system det | SQLite | SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine | :doc:`Phalcon\\Db\\Adapter\\Pdo\\Sqlite <../api/Phalcon_Db_Adapter_Pdo_Sqlite>` | +------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------+ +Implementing your own adapters +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The :doc:`Phalcon\\Db\\AdapterInterface <../api/Phalcon_Db_AdapterInterface>` interface must be implemented in order to create your own database adapters or extend the existing ones. + Database Dialects ----------------- Phalcon encapsulates the specific details of each database engine in dialects. Those provide common functions and SQL generator to the adapters. @@ -37,7 +41,12 @@ Phalcon encapsulates the specific details of each database engine in dialects. T Connecting to Databases ----------------------- -To create a connection it's neccesary instantiate the adapter class. It only requires an array with the connection parameters. The example below shows how to create a connection passing both required and optional parameters: +To create a connection it's neccesary instantiate the adapter class. It only requires an array with the connection parameters. The example +below shows how to create a connection passing both required and optional parameters: + +Implementing your own dialects +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +The :doc:`Phalcon\\Db\\DialectInterface <../api/Phalcon_Db_DialectInterface>` interface must be implemented in order to create your own database dialects or extend the existing ones. .. code-block:: php @@ -101,7 +110,7 @@ Finding Rows $result = $connection->query($sql); // Print each robot name - while ($robot = $result->fetchArray()) { + while ($robot = $result->fetch()) { echo $robot["name"]; } @@ -125,6 +134,8 @@ By default these calls create arrays with both associative and numeric indexes. +--------------------------+-----------------------------------------------------------+ | Phalcon\\Db::FETCH_BOTH | Return an array with both associative and numeric indexes | +--------------------------+-----------------------------------------------------------+ +| Phalcon\\Db::FETCH_OBJ | Return an object instead of an array | ++--------------------------+-----------------------------------------------------------+ .. code-block:: php @@ -134,7 +145,7 @@ By default these calls create arrays with both associative and numeric indexes. $result = $connection->query($sql); $result->setFetchMode(Phalcon\Db::DB_NUM); - while ($robot = $result->fetchArray()) { + while ($robot = $result->fetch()) { echo $robot[0]; } @@ -148,13 +159,13 @@ The Phalcon\\Db::query() returns an instance of :doc:`Phalcon\\Db\\Result\\Pdo < $result = $connection->query($sql); // Traverse the resultset - while ($robot = $result->fetchArray()) { + while ($robot = $result->fetch()) { echo $robot["name"]; } // Seek to the third row $result->seek(2); - $robot = $result->fetchArray(); + $robot = $result->fetch(); // Count the resultset echo $result->numRows(); @@ -162,7 +173,9 @@ The Phalcon\\Db::query() returns an instance of :doc:`Phalcon\\Db\\Result\\Pdo < Binding Parameters ------------------ -Bound parameters is also supported in :doc:`Phalcon\\Db <../api/Phalcon_Db>`. Although there is a minimal performance impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows: +Bound parameters is also supported in :doc:`Phalcon\\Db <../api/Phalcon_Db>`. Although there is a minimal performance impact by using +bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL +injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows: .. code-block:: php diff --git a/en/reference/debug.rst b/en/reference/debug.rst index 0ff45d0c9b6f..3639dc00610f 100755 --- a/en/reference/debug.rst +++ b/en/reference/debug.rst @@ -72,12 +72,14 @@ It's therefore easy to find which file and line of the application's code genera .. code-block:: html - PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO) + PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' + (using password: NO) File=/Applications/MAMP/htdocs/invo/public/index.php Line=74 #0 [internal function]: PDO->__construct('mysql:host=loca...', 'root', '', Array) #1 [internal function]: Phalcon\Db\Adapter\Pdo->connect(Array) - #2 /Applications/MAMP/htdocs/invo/public/index.php(74): Phalcon\Db\Adapter\Pdo->__construct(Array) + #2 /Applications/MAMP/htdocs/invo/public/index.php(74): + Phalcon\Db\Adapter\Pdo->__construct(Array) #3 [internal function]: {closure}() #4 [internal function]: call_user_func_array(Object(Closure), Array) #5 [internal function]: Phalcon\DI->_factory(Object(Closure), Array) @@ -85,7 +87,8 @@ It's therefore easy to find which file and line of the application's code genera #7 [internal function]: Phalcon\DI->getShared('db') #8 [internal function]: Phalcon\Mvc\Model->getConnection() #9 [internal function]: Phalcon\Mvc\Model::_getOrCreateResultset('Users', Array, true) - #10 /Applications/MAMP/htdocs/invo/app/controllers/SessionController.php(83): Phalcon\Mvc\Model::findFirst('email='demo@pha...') + #10 /Applications/MAMP/htdocs/invo/app/controllers/SessionController.php(83): + Phalcon\Mvc\Model::findFirst('email='demo@pha...') #11 [internal function]: SessionController->startAction() #12 [internal function]: call_user_func_array(Array, Array) #13 [internal function]: Phalcon\Mvc\Dispatcher->dispatch() @@ -201,15 +204,19 @@ Once you have xdebug installed, you can use its API to get a more detailed infor In this instance, Xdebug will also show us the variables in the local scope, and a backtrace as well: -.. code-block:: php +.. code-block:: html - Xdebug: stop here! in /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php on line 19 + Xdebug: stop here! in /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php + on line 19 Call Stack: 0.0383 654600 1. {main}() /Applications/MAMP/htdocs/tutorial/public/index.php:0 - 0.0392 663864 2. Phalcon\Mvc\Application->handle() /Applications/MAMP/htdocs/tutorial/public/index.php:37 - 0.0418 738848 3. SignupController->registerAction() /Applications/MAMP/htdocs/tutorial/public/index.php:0 - 0.0419 740144 4. xdebug_print_function_stack() /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php:19 + 0.0392 663864 2. Phalcon\Mvc\Application->handle() + /Applications/MAMP/htdocs/tutorial/public/index.php:37 + 0.0418 738848 3. SignupController->registerAction() + /Applications/MAMP/htdocs/tutorial/public/index.php:0 + 0.0419 740144 4. xdebug_print_function_stack() + /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php:19 Xdebug provides several ways to get debug and trace information regarding the execution of your application using Phalcon. You can check the `XDebug documentation`_ for more information. diff --git a/en/reference/di.rst b/en/reference/di.rst index 5bac889e5987..1906f52b83e8 100644 --- a/en/reference/di.rst +++ b/en/reference/di.rst @@ -275,9 +275,12 @@ Think we had to create this object in many parts of our application. If you ever } -One moment, we returned back to the beginning, we are building again the dependencies inside the component! We can move on and find out a way to solve this problem every time. But it seems that time and again we fall back into bad practices. +One moment, we returned back to the beginning, we are building again the dependencies inside the component! We can move on and find out a way +to solve this problem every time. But it seems that time and again we fall back into bad practices. -A practical and elegant way to solve these problems is to use a container for dependencies. The containers act as the global registry that we saw earlier. Using the container for dependencies as a bridge to obtain the dependencies allows us to reduce the complexity of our component: +A practical and elegant way to solve these problems is to use a container for dependencies. The containers act as the global registry that +we saw earlier. Using the container for dependencies as a bridge to obtain the dependencies allows us to reduce the complexity +of our component: .. code-block:: php @@ -343,14 +346,14 @@ A practical and elegant way to solve these problems is to use a container for de $some->someTask(); -The component now simply access the service it require when it needs it, if it does not requires a service, that is not even initialized saving resources. -The component is now highly decoupled. For example, we can replace the manner in which connections are created, their behavior or any other aspect of them -and that would not affect the component. +The component now simply access the service it require when it needs it, if it does not requires a service, that is not even initialized +saving resources. The component is now highly decoupled. For example, we can replace the manner in which connections are created, +their behavior or any other aspect of them and that would not affect the component. Our approach ------------ -Phalcon\\DI is a component that implements Dependency Injection of services and it's itself a container for them. +Phalcon\\DI is a component that implements Dependency Injection/Location of services and it's itself a container for them. Since Phalcon is highly decoupled, Phalcon\\DI is essential to integrate the different components of the framework. The developer can also use this component to inject dependencies and manage global instances of the different classes used in the application. @@ -478,6 +481,61 @@ Arguments can be passed to the constructor by adding an array parameter to the m $component = $di->get("MyComponent", array("some-parameter", "other")) +Shared services +--------------- +Services can be registered as "shared" services this means that they always will act as singletons_. Once the service is resolved for the first time +the same instance it's returned every time a consumer retrieve the service from the container: + +.. code-block:: php + + setShared('session', function() { + $session = new Phalcon\Session\Adapter\Files(); + $session->start(); + return $session; + }); + + $session = $di->get('session'); // Locates the service for the first time + $session = $di->getSession(); // Returns the first instantiated object + +An alternative way to register services is pass "true" as third parameter of "set": + +.. code-block:: php + + set('session', function() { + //... + }, true); + +Manipulating services individually +---------------------------------- +Once a service is registered in services container, you can retrieve it in other parts of the application individually: + +.. code-block:: php + + set('request', 'Phalcon\Http\Request'); + + //Get the service + $requestService = $di->getService('request'); + + //Change its definition + $requestService->setDefinition(function(){ + return new Phalcon\Http\Request(); + }); + + //Change it to shared + $request->setShared(true); + + //Resolve the service (return a Phalcon\Http\Request instance) + $request = $requestService->resolve(); + Factory Default DI ------------------ Although the decoupled character of Phalcon offers us great freedom and flexibility, maybe we just simply want to use it as a full-stack @@ -493,35 +551,39 @@ Service Name Conventions Although you can register services with the names you want. Phalcon has a seriers of service naming conventions that allow it to get the right services when you need it requires them. -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| Service Name | Description | Default | -+=====================+=============================================+====================================================================================================+ -| dispatcher | Controllers Dispatching Service | :doc:`Phalcon\\Mvc\\Dispatcher <../api/Phalcon_Mvc_Dispatcher>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| router | Routing Service | :doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| url | URL Generator Service | :doc:`Phalcon\\Mvc\\Url <../api/Phalcon_Mvc_Url>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| request | HTTP Request Environment Service | :doc:`Phalcon\\Http\\Request <../api/Phalcon_Http_Request>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| response | HTTP Response Environment Service | :doc:`Phalcon\\Http\\Response <../api/Phalcon_Http_Response>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| filter | Input Filtering Service | :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| flash | Flash Messaging Service | :doc:`Phalcon\\Flash\\Direct <../api/Phalcon_Flash_Direct>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| session | Session Service | :doc:`Phalcon\\Session\\Adapter\\Files <../api/Phalcon_Session_Adapter_Files>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| eventsManager | Events Management Service | :doc:`Phalcon\\Events\\Manager <../api/Phalcon_Events_Manager>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| db | Low-Level Database Connection Service | :doc:`Phalcon\\Db <../api/Phalcon_Db>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| modelsManager | Models Management Service | :doc:`Phalcon\\Mvc\\Model\\Manager <../api/Phalcon_Mvc_Model_Manager>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| modelsMetadata | Models Meta-Data Service | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Memory <../api/Phalcon_Mvc_Model_MetaData_Memory>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ -| transactionManager | Models Transaction Manager Service | :doc:`Phalcon\\Mvc\\Model\\Transaction\\Manager <../api/Phalcon_Mvc_Model_Transaction_Manager>` | -+---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| Service Name | Description | Default | Shared | ++=====================+=============================================+====================================================================================================+========+ +| dispatcher | Controllers Dispatching Service | :doc:`Phalcon\\Mvc\\Dispatcher <../api/Phalcon_Mvc_Dispatcher>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| router | Routing Service | :doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| url | URL Generator Service | :doc:`Phalcon\\Mvc\\Url <../api/Phalcon_Mvc_Url>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| request | HTTP Request Environment Service | :doc:`Phalcon\\Http\\Request <../api/Phalcon_Http_Request>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| response | HTTP Response Environment Service | :doc:`Phalcon\\Http\\Response <../api/Phalcon_Http_Response>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| filter | Input Filtering Service | :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| flash | Flash Messaging Service | :doc:`Phalcon\\Flash\\Direct <../api/Phalcon_Flash_Direct>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| session | Session Service | :doc:`Phalcon\\Session\\Adapter\\Files <../api/Phalcon_Session_Adapter_Files>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| eventsManager | Events Management Service | :doc:`Phalcon\\Events\\Manager <../api/Phalcon_Events_Manager>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| db | Low-Level Database Connection Service | :doc:`Phalcon\\Db <../api/Phalcon_Db>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| modelsManager | Models Management Service | :doc:`Phalcon\\Mvc\\Model\\Manager <../api/Phalcon_Mvc_Model_Manager>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| modelsMetadata | Models Meta-Data Service | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Memory <../api/Phalcon_Mvc_Model_MetaData_Memory>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| transactionManager | Models Transaction Manager Service | :doc:`Phalcon\\Mvc\\Model\\Transaction\\Manager <../api/Phalcon_Mvc_Model_Transaction_Manager>` | Yes | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| modelsCache | Cache backend for models cache | None | - | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ +| viewsCache | Cache backend for views fragments | None | - | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+--------+ Instantiating classes via the Services Container ------------------------------------------------ @@ -549,7 +611,45 @@ the same name. With this behavior we can replace any class by another simply by $myComponent = $di->get('MyOtherComponent'); You can take advantage of this, always instantiating your classes via the services container (even if they aren't registered as services). The DI will -fallback to a valid autoloader to finally load the class. +fallback to a valid autoloader to finally load the class. By doing this, you can easily replace any class in the future by implementing a definition for it. + +Automatic Injecting of the DI itself +------------------------------------ +If a class or component requires the DI itself to locate services, the DI can automatically inject itself to the instances creates by it, To do this, +you need to implement the :doc:`Phalcon\\DI\\InjectionAwareInterface <../api/Phalcon_DI_InjectionAwareInterface>` in your classes: + +.. code-block:: php + + _di = $di; + } + + public function getDi() + { + return $this->_di; + } + + } + +Then once the service is resolved, the $di will be passed to setDi automatically: + +.. code-block:: php + + set('myClass', 'MyClass'); + + //Resolve the service (also $myClass->setDi($di) is automatically called) + $myClass = $di->get('myClass'); Accessing the DI in a static way -------------------------------- @@ -564,9 +664,15 @@ If needed you can access the latest DI created in an static function in the foll public static function someMethod() { - $session = Phalcon\DI::getDefault()->getShared('session'); + //Get the session service + $session = Phalcon\DI::getDefault()->getSession(); } } -.. _`Inversion of Control`: http://en.wikipedia.org/wiki/Inversion_of_control \ No newline at end of file +Implementing your own DI +------------------------ +The :doc:`Phalcon\\DiInterface <../api/Phalcon_DiInterface>` interface must be implemented to create your own DI replacing the one provided by Phalcon. + +.. _`Inversion of Control`: http://en.wikipedia.org/wiki/Inversion_of_control +.. _Singletons: http://en.wikipedia.org/wiki/Singleton_pattern \ No newline at end of file diff --git a/en/reference/dispatching.rst b/en/reference/dispatching.rst index 301460e96335..35568787fa9f 100755 --- a/en/reference/dispatching.rst +++ b/en/reference/dispatching.rst @@ -80,6 +80,27 @@ The following example demonstrates how to attach listeners to this component: return $dispatcher; }); +Instantiated controllers act automatically as listeners for dispatch events, so you can implement methods as callbacks: + +.. code-block:: php + + dispatcher->forward(array("controller" => "post", "action" => "index")); + $this->dispatcher->forward(array( + "controller" => "post", + "action" => "index" + )); } } Keep in mind that making a "forward" is not the same as making an HTTP redirect. Although they apparently got the same result. -The "forward" doesn't reloads the current page, all the redirection occurs in a single request, while the HTTP redirect needs two requests +The "forward" doesn't reload the current page, all the redirection occurs in a single request, while the HTTP redirect needs two requests to complete the process. +More forwarding examples: + +.. code-block:: php + + dispatcher->forward(array( + "action" => "search" + )); + + // Forward flow to another action in the current controller + // passing parameters + $this->dispatcher->forward(array( + "action" => "search", + "params" => array(1, 2, 3) + )); + + // Forward flow to another action in the current controller + // passing parameters + $this->dispatcher->forward(array( + "action" => "search", + "params" => array(1, 2, 3) + )); + +A forward action accepts the following parameters: + ++----------------+--------------------------------------------------------+ +| Parameter | Triggered | ++================+========================================================+ +| controller | A valid controller name to forward to. | ++----------------+--------------------------------------------------------+ +| action | A valid action name to forward to. | ++----------------+--------------------------------------------------------+ +| params | An array of parameters for the action | ++----------------+--------------------------------------------------------+ +| namespace | A valid namespace name where the controller is part of | ++----------------+--------------------------------------------------------+ + Getting Parameters ------------------ When a route provides named parameters you can receive them in a controller, a view or any other component that extends @@ -150,7 +213,7 @@ Using the :doc:`EventsManager ` it's possible to insert a hook point bef set('dispatcher', function(){ + $di->setShared('dispatcher', function() { //Create/Get an EventManager $eventsManager = new Phalcon\Events\Manager(); @@ -189,3 +252,6 @@ Using the :doc:`EventsManager ` it's possible to insert a hook point bef return $dispatcher; }); +Implementing your own Dispatcher +-------------------------------- +The :doc:`Phalcon\\Mvc\\DispatcherInterface <../api/Phalcon_Mvc_DispatcherInterface>` interface must be implemented to create your own dispatcher replacing the one providing by Phalcon. diff --git a/en/reference/events.rst b/en/reference/events.rst index bd0f2de6d8dc..04c5f563d91e 100644 --- a/en/reference/events.rst +++ b/en/reference/events.rst @@ -161,7 +161,7 @@ This component is EventsManager aware; when its method "someTask" is executed it _eventsManager = $eventsManager; } + public function getEventsManager() + { + return $this->_eventsManager + } + public function someTask() { $this->_eventsManager->fire("my-component:beforeSomeTask", $this); @@ -205,7 +210,7 @@ the same name. Now let's create a listener to this component: } -A listener is simply a class that implements any of all the events triggered by the component. Now let's all working together: +A listener is simply a class that implements any of all the events triggered by the component. Now let's make everything work together: .. code-block:: php @@ -257,7 +262,7 @@ In a listener the third parameter also receives this data: print_r($event->getData()); }); -If a listener it's only interested in listening a specific type of event you can attach a listener directly: +If a listener it is only interested in listening a specific type of event you can attach a listener directly: .. code-block:: php @@ -267,3 +272,39 @@ If a listener it's only interested in listening a specific type of event you can $eventManager->attach('my-component:beforeSomeTask', function($event, $component) { //... }); + +Event Propagation/Cancelation +----------------------------- +Many listeners may be added to the same event manager, this means that for the same type of event many listeners can be notified. +The listeners are notified in the order they were registered in the EventsManager. Some events are cancellable, indicating that +these may be stopped preventing other listeners are notified about the event: + +.. code-block:: php + + attach('db', function($event, $connection){ + + //We stop the event if it is cancelable + if ($event->isCancelable()) { + //Stop the event, so other listeners will not be notified about this + $event->stop(); + } + + //... + + }); + +By default events are cancelable, even most of events produced by the framework are cancelables. You can fire a not-cancelable event +by passing "false" in the four parameter of fire: + +.. code-block:: php + + fire("my-component:afterSomeTask", $this, $extraData, false); + +Implementing your own EventsManager +----------------------------------- +The :doc:`Phalcon\\Events\\ManagerInterface <../api/Phalcon_Events_ManagerInterface>` interface must be implemented to create your own +EventsManager replacing the one provided by Phalcon. \ No newline at end of file diff --git a/en/reference/filter.rst b/en/reference/filter.rst index b56ddad754fe..b2db5eddab5a 100755 --- a/en/reference/filter.rst +++ b/en/reference/filter.rst @@ -151,9 +151,11 @@ Or, if you prefer, you can implement the filter in a class: ` interface must be implemented to create your own filtering service replacing the one providing by Phalcon. + .. _Data Filtering at PHP Documentation: http://www.php.net/manual/en/book.filter.php .. _strip_tags: http://www.php.net/manual/en/function.strip-tags.php .. _trim: http://www.php.net/manual/en/function.trim.php diff --git a/en/reference/flash.rst b/en/reference/flash.rst index 3255c3801b1b..e579d0a9f0cc 100644 --- a/en/reference/flash.rst +++ b/en/reference/flash.rst @@ -1,7 +1,7 @@ Flashing Messages ================= Flash messages are used to notify the user about the state of actions he/she made or simply show information to the users. This kind of -messages can be generated using +messages can be generated using this component Adapters -------- @@ -174,4 +174,4 @@ In this case you need to print manually the messages in the corresponding view:

flashSession->output() ?>

-The attribute 'flashSession' is how the flash was previously set into the dependency injector. +The attribute 'flashSession' is how the flash was previously set into the dependency injection container. diff --git a/en/reference/install.rst b/en/reference/install.rst index 8ddc4cd6d4d8..6cead8b02839 100755 --- a/en/reference/install.rst +++ b/en/reference/install.rst @@ -1,19 +1,23 @@ Installation ============ -PHP extensions require a slightly different installation method to a traditional php-based library or framework. You can either download a binary package for the system of your choice or build it from the sources. +PHP extensions require a slightly different installation method to a traditional php-based library or framework. You can either +download a binary package for the system of your choice or build it from the sources. -During the last few months, we have extensively researched PHP's behavior, investigating areas for significant optimizations (big or small). Through understanding of the Zend Engine, we managed to remove unecessary validations, compacted code, performed optimizations and generated low-level solutions so as to achieve maximum performance from Phalcon. +During the last few months, we have extensively researched PHP's behavior, investigating areas for significant +optimizations (big or small). Through understanding of the Zend Engine, we managed to remove unecessary validations, +compacted code, performed optimizations and generated low-level solutions so as to achieve maximum performance +from Phalcon. .. highlights:: - Phalcon compiles from PHP 5.3.1, but because of old PHP bugs causing memory leaks, we highly recommend you to use at least PHP 5.3.11 or greater. + Phalcon compiles from PHP 5.3.1, but because of old PHP bugs causing memory leaks, we highly recommend you to use at least PHP 5.3.11 or greater. Windows ------- To use phalcon on Windows you can download a DLL library. Edit your php.ini file and then append at the end: - extension=php_phalcon.dll + extension=php_phalcon.dll Restart your webserver. @@ -21,20 +25,19 @@ The following screencast is a step-by-step guide to install Phalcon on Windows: .. raw:: html -
+
Related Guides ^^^^^^^^^^^^^^ .. toctree:: - :maxdepth: 1 + :maxdepth: 1 - xampp - wamp + xampp + wamp Unix/Linux ---------- - On a Unix/Linux system you can easily compile and install the extension from the source code: Requirements @@ -47,13 +50,13 @@ Prerequisite packages are: .. code-block:: bash - #Ubuntu - sudo apt-get install php5-dev php5-mysql gcc - sudo apt-get install git-core + #Ubuntu + sudo apt-get install php5-dev php5-mysql gcc + sudo apt-get install git-core - #Suse - yast2 -i php5-pear php5-dev php5-mysql gcc - yast2 -i git-core + #Suse + yast2 -i php5-pear php5-dev php5-mysql gcc + yast2 -i git-core Compilation ^^^^^^^^^^^ @@ -61,15 +64,15 @@ Creating the extension: .. code-block:: bash - git clone git://github.com/phalcon/cphalcon.git - cd cphalcon/build - sudo ./install + git clone git://github.com/phalcon/cphalcon.git + cd cphalcon/build + sudo ./install Add extension to your php.ini .. code-block:: bash - extension=phalcon.so + extension=phalcon.so Restart the webserver @@ -79,14 +82,14 @@ A port is available for FreeBSD. Just only need these simple line commands to in .. code-block:: bash - pkg_add -r phalcon + pkg_add -r phalcon or .. code-block:: bash - export CFLAGS="-O2 -fno-delete-null-pointer-checks" - cd /usr/ports/www/phalcon && make install clean + export CFLAGS="-O2 -fno-delete-null-pointer-checks" + cd /usr/ports/www/phalcon && make install clean Installation Notes ^^^^^^^^^^^^^^^^^^ @@ -94,7 +97,8 @@ Installation Notes Installation notes for Web Servers: .. toctree:: - :maxdepth: 1 + :maxdepth: 1 - nginx + apache + nginx diff --git a/en/reference/loader.rst b/en/reference/loader.rst index 2755bf6a0dce..4ad54c9663c2 100755 --- a/en/reference/loader.rst +++ b/en/reference/loader.rst @@ -116,7 +116,7 @@ maintenance of the class list very cumbersome and it is not recommended. // Creates the autoloader $loader = new \Phalcon\Loader(); - // Register some directories + // Register some classes $loader->registerClasses( array( "Some" => "library/OtherComponent/Other/Some.php", @@ -147,6 +147,25 @@ are using additional extensions you could set it with the method "setExtensions" //Set file extensions to check $loader->setExtensions(array("php", "inc", "phb")); +Modifying current strategies +---------------------------- +Additional data could be added to the existing values for strategies in the following way: + +.. code-block:: php + + registerDirs( + array( + "../app/library/" + "../app/plugins/" + ), + true + ); + +Passing "true" as second parameter will merge the current values with new ones in any strategy. + Autoloading Events ------------------ In the following example, the EventsManager is working with the class loader, allowing us to obtain debugging information regarding the flow of operation: @@ -166,7 +185,7 @@ In the following example, the EventsManager is working with the class loader, al )); //Listen all the loader events - $eventsManager->attach('loader', function(){ + $eventsManager->attach('loader', function($event, $loader) { if ($event->getType() == 'beforeCheckPath') { echo $loader->getCheckedPath(); } diff --git a/en/reference/logging.rst b/en/reference/logging.rst index 1bbcb5432f6b..82417196856f 100755 --- a/en/reference/logging.rst +++ b/en/reference/logging.rst @@ -102,3 +102,6 @@ change this mode passing additional options to the constructor: .. _fopen: http://php.net/manual/en/function.fopen.php +Implementing your own adapters +------------------------------ +The :doc:`Phalcon\\Logger\\AdapterInterface <../api/Phalcon_Logger_AdapterInterface>` interface must be implemented in order to create your own logger adapters or extend the existing ones. \ No newline at end of file diff --git a/en/reference/models.rst b/en/reference/models.rst index 7ed6cf64cf35..2b2aa632dd7d 100755 --- a/en/reference/models.rst +++ b/en/reference/models.rst @@ -138,13 +138,20 @@ how to query one or more records from a model: echo "There are ", count($robots), "\n"; // Get and print virtual robots ordered by name - $robots = Robots::find(array("type = 'virtual'", "order" => "name")); + $robots = Robots::find(array( + "type = 'virtual'", + "order" => "name" + )); foreach ($robots as $robot) { echo $robot->name, "\n"; } // Get first 100 virtual robots ordered by name - $robots = Robots::find(array("type = 'virtual'", "order" => "name", "limit" => 100)); + $robots = Robots::find(array( + "type = 'virtual'", + "order" => "name", + "limit" => 100 + )); foreach ($robots as $robot) { echo $robot->name, "\n"; } @@ -190,27 +197,27 @@ Both find() and findFirst() methods accept an associative array specifying the s The available query options are: -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| Parameter | Description | Example | -+=============+==============================================================================================================================================================================================+=========================================================================+ -| conditions | Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon_model assumes the first parameter are the conditions. | "conditions" => "name LIKE 'steve%'" | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| bind | Bind is used together with options, by replacing placeholders and escaping values thus increasing security | "bind" => array("status" => "A", "type" => "some-time") | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| bindTypes | When binding parameters, you can use this parameter to define additional casting to the bound parameters increasing even more the security | "bindTypes" => array(Column::BIND_TYPE_STR, Column::BIND_TYPE_INT) | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| order | Is used to sort the resultset. Use one or more fields separated by commas. | "order" => "name DESC, status" | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| limit | Limit the results of the query to results to certain range | "limit" => 10 | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| group | Allows to collect data across multiple records and group the results by one or more columns | "group" => "name, status" | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| for_update | With this option, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` reads the latest available data, setting exclusive locks on each row it reads | "for_update" => true | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| shared_lock | With this option, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` reads the latest available data, setting shared locks on each row it reads | "shared_lock" => true | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ -| cache | Cache the resulset, reducing the continuous access to the relational system | "cache" => array("lifetime" => 3600, "key" => "my-find-key") | -+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| Parameter | Description | Example | ++=============+==================================================================================================================================================================================================+=========================================================================+ +| conditions | Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon\Mvc\Model assumes the first parameter are the conditions. | "conditions" => "name LIKE 'steve%'" | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| bind | Bind is used together with options, by replacing placeholders and escaping values thus increasing security | "bind" => array("status" => "A", "type" => "some-time") | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| bindTypes | When binding parameters, you can use this parameter to define additional casting to the bound parameters increasing even more the security | "bindTypes" => array(Column::BIND_TYPE_STR, Column::BIND_TYPE_INT) | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| order | Is used to sort the resultset. Use one or more fields separated by commas. | "order" => "name DESC, status" | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| limit | Limit the results of the query to results to certain range | "limit" => 10 | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| group | Allows to collect data across multiple records and group the results by one or more columns | "group" => "name, status" | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| for_update | With this option, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` reads the latest available data, setting exclusive locks on each row it reads | "for_update" => true | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| shared_lock | With this option, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` reads the latest available data, setting shared locks on each row it reads | "shared_lock" => true | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| cache | Cache the resulset, reducing the continuous access to the relational system | "cache" => array("lifetime" => 3600, "key" => "my-find-key") | ++-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ If you prefer, there is also available a way to create queries in an object oriented way, instead of using an array of parameters: @@ -226,7 +233,9 @@ If you prefer, there is also available a way to create queries in an object orie The static method query() returns a :doc:`Phalcon\\Mvc\\Model\\Criteria <../api/Phalcon_Mvc_Model_Criteria>` object that is friendly with IDE autocompleters. -Phalcon also offers you the possibility to query records using a high level, object oriented, SQL-like language called :doc:`PHQL `. + +All the queries are internally handled as :doc:`PHQL ` queries. PHQL is a high level, object oriented and SQL-like language. +This language provide you more features to perform queries like joining other models, define groupings, add agreggations etc. Model Resultsets ^^^^^^^^^^^^^^^^ @@ -323,18 +332,41 @@ to SQL injection attacks. Both string and integer placeholders are supported. Bi // Query robots binding parameters with string placeholders $conditions = "name = :name: AND type = :type:"; - $parameters = array("name" => "Robotina", "type" => "maid"); - $robots = Robots::find(array($conditions, "bind" => $parameters)); + + //Parameters whose keys are the same as placeholders + $parameters = array( + "name" => "Robotina", + "type" => "maid" + ); + + //Perform the query + $robots = Robots::find(array( + $conditions, + "bind" => $parameters + )); // Query robots binding parameters with integer placeholders $conditions = "name = ?1 AND type = ?2"; $parameters = array(1 => "Robotina", 2 => "maid"); - $robots = Robots::find(array($conditions, "bind" => $parameters)); + $robots = Robots::find(array( + $conditions, + "bind" => $parameters + )); // Query robots binding parameters with both string and integer placeholders $conditions = "name = :name: AND type = ?1"; - $parameters = array("name" => "Robotina", 1 => "maid"); - $robots = Robots::find(array($conditions, "bind" => $parameters)); + + //Parameters whose keys are the same as placeholders + $parameters = array( + "name" => "Robotina", + 1 => "maid" + ); + + //Perform the query + $robots = Robots::find(array( + $conditions, + "bind" => $parameters + )); When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case "1" or "2" are considered strings and not numbers, so the placeholder could not be successfully replaced. @@ -343,16 +375,26 @@ Strings are automatically escaped using PDO_. This function takes into account t the correct charset in the connection parameters or in the database configuration, as a wrong charset will produce undesired effects when storing or retrieving data. -Additionally you can set the parameter "bindTypes", this allows to define how the parameters should be binded according to its data type: +Additionally you can set the parameter "bindTypes", this allows defining how the parameters should be bound according to its data type: .. code-block:: php "Robotina", + "year" => 2008 + ); + + //Casting Types + $types = array( + Phalcon\Db\Column::BIND_PARAM_STR, + Phalcon\Db\Column::BIND_PARAM_INT + ); + // Query robots binding parameters with string placeholders $conditions = "name = :name: AND year = :year:"; - $parameters = array("name" => "Robotina", "year" => 2008); - $types = array(Phalcon\Db\Column::BIND_TYPE_STR, Phalcon\Db\Column::BIND_TYPE_INT); $robots = Robots::find(array( $conditions, "bind" => $parameters, @@ -424,7 +466,7 @@ The following schema shows 3 tables whose relations will serve us as an example * The model "Robots" has many "RobotsParts". * The model "Parts" has many "RobotsParts". -* The model "RobotsParts" belongs to "Robots" and "Parts" models as a one-to-many relation. +* The model "RobotsParts" belongs to both "Robots" and "Parts" models as a one-to-many relation. The models with their relations could be implemented as follows: @@ -501,11 +543,11 @@ retrieving related results with using the magic method and without: $robotsParts = $robot->getRobotsParts(); // Only parts that match conditions - $robotsParts = $robot->getRobotsParts("created_at='2012-03-15'"); + $robotsParts = $robot->getRobotsParts("created_at = '2012-03-15'"); // Or using bound parameters $robotsParts = $robot->getRobotsParts(array( - "created_at=:date:", + "created_at = :date:", "bind" => array("date" => "2012-03-15" ))); @@ -858,6 +900,30 @@ Also the method executes associated validators, virtual foreign keys and events echo "Great, a new robot was saved successfully!"; } +An array could be passed to "save" to avoid assign every column manually. Phalcon\\Mvc\\Model will check if there are setters implemented for +the columns passed in the array giving priority to them instead of assign directly the values of the attributes: + +.. code-block:: php + + save(array( + "type" => "mechanical", + "name" => "Astro Boy", + "year" => 1952 + )); + +Values assigned directly or via the array of attributes are escaped/sanitized according to the related attribute data type. So you can pass +an insecure array without worrying about possible SQL injections: + +.. code-block:: php + + save($_POST); + Create/Update with Certainty ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When an application has a lot of competition, maybe we expect to create a record but that is actually updated. This could happen if we use @@ -883,6 +949,8 @@ created we can change save by "create" or "update": echo "Great, a new robot was created successfully!"; } +These methods "create" and "update" also accept an array of values as parameter. + Auto-generated identity columns ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Some models may have identity columns. These columns usually are the primary key of the mapped table. :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` @@ -1057,7 +1125,7 @@ If we want all objects created in our application use the same EventsManager the set('modelsManager', function() { + $di->setShared('modelsManager', function() { $eventsManager = new Phalcon\Events\Manager(); @@ -1178,7 +1246,10 @@ In addition to the built-in validatiors, you can create your own validators: get(); @@ -1469,7 +1543,7 @@ Transactions can be used to delete many records in a consistent way: echo "Robots were deleted successfully!"; - } catch(Phalcon\Mvc\Model\Transaction\Failed $e) { + } catch(TxFailed $e) { echo "Failed, reason: ", $e->getMessage(); } @@ -1480,7 +1554,7 @@ is performed. You can use the service container to create an overall transaction set('transactions', function(){ + $di->setShared('transactions', function(){ return new Phalcon\Mvc\Model\Transaction\Manager(); }); @@ -1496,7 +1570,7 @@ Then access it from a controller or view: { //Obtain the TransactionsManager from the DI container - $manager = $this->di->getShared('transactions'); + $manager = $this->di->getTransactions(); //Request a transaction $transaction = $manager->get(); @@ -1505,6 +1579,63 @@ Then access it from a controller or view: } +Independent Column Mapping +-------------------------- +The ORM supports a independent column map, which allows the developer to use different column names in the model to the ones in +the table. Phalcon will recognize the new column names and will rename them accordingly to match the respective columns in the database. +This is a great feature when one needs to rename fields in the database without having to worry about all the queries +in the code. A change in the column map in the model will take care of the rest. For example: + +.. code-block:: php + + 'code', + 'the_name' => 'theName', + 'the_type' => 'theType', + 'the_year' => 'theYear' + ); + } + + } + +Then you can use the new names naturally in your code: + +.. code-block:: php + + theName, "\n"; + + //Get robots ordered by type + $robot = Robots::find(array('order' => 'theType DESC')); + foreach ($robots as $robot) { + echo 'Code: ', $robot->code, "\n"; + } + + //Create a robot + $robot = new Robots(); + $robot->code = '10101'; + $robot->theName = 'Bender'; + $robot->theType = 'Industrial'; + $robot->theYear = 2999; + $robot->save(); + +Take into consideration the following the next when renaming your columns: + +* References to attributes in relationships/validators must use the new names +* Refer the column names will result in an exception by the ORM + Models Meta-Data ---------------- To speed up development :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` helps you to query fields and constraints from tables @@ -1553,7 +1684,7 @@ As other ORM's dependencies, the metadata manager is requested from the services set('modelsMetadata', function() { + $di->setShared('modelsMetadata', function() { // Create a meta-data manager with APC $metaData = new Phalcon\Mvc\Model\MetaData\Apc( @@ -1625,7 +1756,7 @@ The following example shows how to define the meta-data manually: //The identity column MetaData::MODELS_IDENTITY_COLUMN => 'id', - //How every column must be binded/casted + //How every column must be bound/casted MetaData::MODELS_DATA_TYPES_BIND => array( 'id' => Column::BIND_PARAM_INT, 'name' => Column::BIND_PARAM_STR, @@ -1641,11 +1772,9 @@ The following example shows how to define the meta-data manually: } -Setting a different schema --------------------------- -Models may are mapped to tables that are in different schemas/databases than the default. You can use the getSchema method to define that: - -Then, in the Initialize method, we define the connection service for the model: +Pointing to a different schema +------------------------------ +If a model is mapped to a table that is in a different schemas/databases than the default. You can use the getSchema method to define that: .. code-block:: php @@ -1777,14 +1906,14 @@ this you can diagnose performance problems and to discover bottlenecks. $di->set('profiler', function(){ return new Phalcon\Db\Profiler(); - }) + }); - $di->set('db', function() use($di) { + $di->set('db', function() use ($di) { $eventsManager = new Phalcon\Events\Manager(); //Get a shared instance of the DbProfiler - $profiler = $di->getShared('profiler'); + $profiler = $di->getProfiler(); //Listen all the database events $eventsManager->attach('db', function($event, $connection) use ($profiler) { @@ -1846,10 +1975,10 @@ You may be required to access the application services within a model, the follo public function notSave() { //Obtain the flash service from the DI container - $flash = $this->getDI()->getShared('flash'); + $flash = $this->getDI()->getFlash(); //Show validation messages - foreach($this->getMesages() as $message) { + foreach ($this->getMesages() as $message) { $flash->error((string) $message); } } diff --git a/en/reference/namespaces.rst b/en/reference/namespaces.rst index a9fce69863e2..aabfbc2f4cf8 100644 --- a/en/reference/namespaces.rst +++ b/en/reference/namespaces.rst @@ -21,7 +21,7 @@ Use an autoload strategy that takes into account the namespaces, for example wit ) ); -Specify in the routes a full class name in the controller path: +Specify it in the routes as a full class name in the controller path: .. code-block:: php @@ -35,8 +35,23 @@ Specify in the routes a full class name in the controller path: ) ); +Passing it as part of the route: + +.. code-block:: php + + add( + "/:namespace/admin/users/my-profile", + array( + "namespace" => 1, + "controller" => "Users", + "action" => "profile", + ) + ); + If you are only working with the same namespace for every controller in your application, then you can define a default namespace -in the Dispatcher. by doing this you don't need to specify a full class name in the router path. +in the Dispatcher, by doing this you don't need to specify a full class name in the router path: .. code-block:: php diff --git a/en/reference/nginx.rst b/en/reference/nginx.rst index 396a2d0c0aea..be0ac04dfc59 100755 --- a/en/reference/nginx.rst +++ b/en/reference/nginx.rst @@ -37,7 +37,7 @@ Dedicated Instance # otherwise rewrite it if (!-e $request_filename) { rewrite ^(.+)$ /index.php?_url=$1 last; - break; + break; } } diff --git a/en/reference/pagination.rst b/en/reference/pagination.rst index c54598f4c51a..18b6ab567307 100755 --- a/en/reference/pagination.rst +++ b/en/reference/pagination.rst @@ -90,3 +90,35 @@ The $page object has the following attributes: | last | The last page in the set of records | +---------+--------------------------------------------------------+ +Implementing your own adapters +------------------------------ +The :doc:`Phalcon\\Paginator\\AdapterInterface <../api/Phalcon_Paginator_AdapterInterface>` interface must be implemented in order to create your own paginator adapters or extend the existing ones: + +.. code-block:: php + + brands->name, "\n"; } +If an alias is used to rename the models in the query, those will be used to name the attributes in the every row of the result: + +.. code-block:: php + + executeQuery($phql); + foreach ($rows as $row) + { + echo "Car: ", $row->c->name, "\n"; + echo "Brand: ", $row->b->name, "\n"; + } + Aggregations ^^^^^^^^^^^^ The following examples show how to use aggregations in PHQL: @@ -331,6 +351,14 @@ The following examples show how to use aggregations in PHQL: echo $row["maximum"], ' ', $row["minimum"], "\n"; } + // Count distinct used brands + $phql = "SELECT COUNT(DISTINCT brand_id) AS brandId FROM Cars"; + $rows = $manager->executeQuery($phql); + foreach ($rows as $row) + { + echo $row->brandId, "\n"; + } + Conditions ^^^^^^^^^^ Conditions allow us to filter the set of records we want to query. The WHERE clause allows to to that: @@ -364,6 +392,9 @@ Conditions allow us to filter the set of records we want to query. The WHERE cla $phql = "SELECT * FROM Cars WHERE Cars.id NOT IN (430, 431)"; $cars = $manager->executeQuery($phql); + $phql = "SELECT * FROM Cars WHERE Cars.id BETWEEN 1 AND 100"; + $cars = $manager->executeQuery($phql); + Also, as part of PHQL, prepared parameters automatically escape the input data, introducing more security: .. code-block:: php @@ -376,8 +407,9 @@ Also, as part of PHQL, prepared parameters automatically escape the input data, $phql = "SELECT * FROM Cars WHERE Cars.name = ?0"; $cars = $manager->executeQuery($phql, array(0 => 'Lamborghini Espada')); -Creating Rows -------------- + +Inserting Data +-------------- With PHQL is possible insert data using the familiar INSERT statement: .. code-block:: php @@ -447,7 +479,7 @@ because the price does not meet the business rule that we implemented: } } -Updating Rows +Updating Data ------------- Updating rows is very similar than Inserting rows. As you may know, the instruction to update records is UPDATE. When a record is updated the events related to the update operation @@ -480,9 +512,9 @@ will be executed for each row. ) ); -Deleting Rows +Deleting Data ------------- -When a record is deleted the events related to the delete operation will be executed for each row. +When a record is deleted the events related to the delete operation will be executed for each row: .. code-block:: php @@ -496,5 +528,134 @@ When a record is deleted the events related to the delete operation will be exec $phql = "DELETE FROM Cars WHERE id > 100"; $manager->executeQuery($phql); + // Using placeholders + $phql = "DELETE FROM Cars WHERE id BETWEEN :initial: AND :final:"; + $manager->executeQuery( + $phql, + array( + 'initial' => 1, + 'final' => '100 + ) + ); + +Creating queries using the Query Builder +---------------------------------------- +A builder is available to create PHQL queries without the need to write PHQL statements that is also IDE friendly: + +.. code-block:: php + + createBuilder() + >join('RobotsParts'); + ->limit(20); + ->order('Robots.name') + ->getQuery() + ->execute(); + +That is the same as: + +.. code-block:: php + + executeQuery($phql); + +More examples of the builder: + +.. code-block:: php + + from('Robots') + // 'SELECT Robots.* FROM Robots' + + // 'SELECT Robots.*, RobotsParts.* FROM Robots, RobotsParts' + $builder->from(array('Robots', 'RobotsParts')) + + // 'SELECT * FROM Robots' + $phql = $builder->columns('*') + ->from('Robots') + + // 'SELECT id, name FROM Robots' + $builder->columns(array('id', 'name')) + ->from('Robots') + + // 'SELECT id, name FROM Robots' + $builder->columns('id, name') + ->from('Robots') + + // 'SELECT Robots.* FROM Robots WHERE Robots.name = "Voltron"' + $builder->from('Robots') + ->where('Robots.name = "Voltron"') + + // 'SELECT Robots.* FROM Robots WHERE Robots.id = 100' + $builder->from('Robots') + ->where(100) + + // 'SELECT Robots.* FROM Robots GROUP BY Robots.name' + $builder->from('Robots') + ->groupBy('Robots.name') + + // 'SELECT Robots.* FROM Robots GROUP BY Robots.name, Robots.id' + $builder->from('Robots') + ->groupBy(array('Robots.name', 'Robots.id')) + + // 'SELECT Robots.name, SUM(Robots.price) FROM Robots GROUP BY Robots.name' + $builder->columns(array('Robots.name', 'SUM(Robots.price)')) + ->from('Robots') + ->groupBy('Robots.name') + + // 'SELECT Robots.name, SUM(Robots.price) FROM Robots + // GROUP BY Robots.name HAVING SUM(Robots.price) > 1000' + $builder->columns(array('Robots.name', 'SUM(Robots.price)')) + ->from('Robots') + ->groupBy('Robots.name') + ->having('SUM(Robots.price) > 1000') + + // 'SELECT Robots.* FROM Robots JOIN RobotsParts'); + $builder->from('Robots') + ->join('RobotsParts') + + // 'SELECT Robots.* FROM Robots JOIN RobotsParts AS p'); + $builder->from('Robots') + ->join('RobotsParts', null, 'p') + + // 'SELECT Robots.* FROM Robots JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p'); + $builder->from('Robots') + ->join('RobotsParts', 'Robots.id = RobotsParts.robots_id', 'p') + + // 'SELECT Robots.* FROM Robots + // JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p + // JOIN Parts ON Parts.id = RobotsParts.parts_id AS t' + $builder->from('Robots') + ->join('RobotsParts', 'Robots.id = RobotsParts.robots_id', 'p') + ->join('Parts', 'Parts.id = RobotsParts.parts_id', 't') + + // 'SELECT r.* FROM Robots AS r' + $builder->addFrom('Robots', 'r') + + // 'SELECT Robots.*, p.* FROM Robots, Parts AS p' + $builder->from('Robots') + ->addFrom('Parts', 'p') + + // 'SELECT r.*, p.* FROM Robots AS r, Parts AS p' + $builder->from(array('r' => 'Robots')) + ->addFrom('Parts', 'p') + + // 'SELECT r.*, p.* FROM Robots AS r, Parts AS p'); + $builder->from(array('r' => 'Robots', 'p' => 'Parts')) + + // 'SELECT Robots.* FROM Robots LIMIT 10' + $builder->from('Robots') + ->limit(10) + + // 'SELECT Robots.* FROM Robots LIMIT 10 OFFSET 5' + $builder->from('Robots') + ->limit(10, 5) + .. _SQLite: http://en.wikipedia.org/wiki/Lemon_Parser_Generator \ No newline at end of file diff --git a/en/reference/request.rst b/en/reference/request.rst index 7fa668a9cdbf..433e1c25c4f9 100755 --- a/en/reference/request.rst +++ b/en/reference/request.rst @@ -27,9 +27,9 @@ contain the values present in forms submitted or the parameters sent via the URL never sanitized and can contain illegal characters or even malicious code, which can lead to `SQL injection`_ or `Cross Site Scripting (XSS)`_ attacks. -:doc:`Phalcon\\HTTP\\Request <../api/Phalcon_Http_Request>` allows you to access the values stored in the $_GET -and $_POST arrays and sanitize or filter them with :doc:`Phalcon\\Filter <../api/Phalcon_Filter>`. The following -examples offer the same behavior: +:doc:`Phalcon\\HTTP\\Request <../api/Phalcon_Http_Request>` allows you to access the values stored in the $_REQUEST, +$_GET and $_POST arrays and sanitize or filter them with the 'filter' service, (by default +:doc:`Phalcon\\Filter `). The following examples offer the same behavior: .. code-block:: php @@ -37,6 +37,7 @@ examples offer the same behavior: // Manually applying the filter $filter = new Phalcon\Filter(); + $email = $filter->sanitize($_POST["user_email"], "email"); // Manually applying the filter to the value @@ -46,6 +47,12 @@ examples offer the same behavior: // Automatically applying the filter $email = $request->getPost("user_email", "email"); + // Setting a default value if the param is null + $email = $request->getPost("user_email", "email", "some@example.com"); + + // Setting a default value if the param is null without filtering + $email = $request->getPost("user_email", null, "some@example.com"); + Accessing the Request from Controllers -------------------------------------- @@ -99,7 +106,13 @@ an object-oriented way to achieve this task: if ($this->request->hasFiles() == true) { // Print the real file names and sizes foreach ($this->request->getUploadedFiles() as $file) { + + //Print file details echo $file->getName(), " ", $file->getSize(), "\n"; + + + //Move the file into the application + $file->moveTo('files/'); } } } diff --git a/en/reference/response.rst b/en/reference/response.rst index 0891d7445667..0795070c0d3d 100644 --- a/en/reference/response.rst +++ b/en/reference/response.rst @@ -15,7 +15,7 @@ component designed to achieve this task. HTTP responses are usually composed by $response->setRawHeader(404, "Not Found"); //Set the content of the response - $response->setContent("Sorry, the page doesn't exists"); + $response->setContent("Sorry, the page doesn't exist"); //Send response to the client $response->send(); @@ -68,3 +68,21 @@ With :doc:`Phalcon\\HTTP\\Response <../api/Phalcon_Http_Response>` you can also //Making a redirection specifyng the HTTP status code $response->redirect("http://www.example.com/new-location", true, 301); +All internal URIs are generated using the 'url' service (by default :doc:`Phalcon\\Mvc\\Url `), in this way you can make redirections +based on the routes you've currently defined in the application: + +.. code-block:: php + + redirect(array( + "for" => "index-lang", + "lang" => "jp", + "controller" => "index" + )); + +Note that making a redirection doesn't disable the view component, so if there is a view asociated with the current action it +will be executed anyways. You can disable the view from a controller by executing $this->view->disable(); + + diff --git a/en/reference/routing.rst b/en/reference/routing.rst index 558551fc4611..ed5204cda21c 100755 --- a/en/reference/routing.rst +++ b/en/reference/routing.rst @@ -87,17 +87,24 @@ first subpattern matched (:controller) is the controller part of the route, the These placeholders help writing regular expressions that are more readable for developers and easier to understand. The following placeholders are supported: -+--------------+--------------------+--------------------------------------------------------------------+ -| Placeholder | Regular Expression | Usage | -+==============+====================+====================================================================+ -| /:module | /([a-zA-Z0-9\_]+) | Matches a valid module name with alpha-numeric characters only | -+--------------+--------------------+--------------------------------------------------------------------+ -| /:controller | /([a-zA-Z0-9\_]+) | Matches a valid controller name with alpha-numeric characters only | -+--------------+--------------------+--------------------------------------------------------------------+ -| /:action | /([a-zA-Z0-9\_]+) | Matches a valid action name with alpha-numeric characters only | -+--------------+--------------------+--------------------------------------------------------------------+ -| /:params | (/.*)* | Matches a list of optional words separated by slashes | -+--------------+--------------------+--------------------------------------------------------------------+ ++--------------+---------------------+--------------------------------------------------------------------+ +| Placeholder | Regular Expression | Usage | ++==============+=====================+====================================================================+ +| /:module | /([a-zA-Z0-9\_\-]+) | Matches a valid module name with alpha-numeric characters only | ++--------------+---------------------+--------------------------------------------------------------------+ +| /:controller | /([a-zA-Z0-9\_\-]+) | Matches a valid controller name with alpha-numeric characters only | ++--------------+---------------------+--------------------------------------------------------------------+ +| /:action | /([a-zA-Z0-9\_]+) | Matches a valid action name with alpha-numeric characters only | ++--------------+---------------------+--------------------------------------------------------------------+ +| /:params | (/.*)* | Matches a list of optional words separated by slashes | ++--------------+---------------------+--------------------------------------------------------------------+ +| /:namespace | /([a-zA-Z0-9\_\-]+) | Matches a single level namespace name | ++--------------+---------------------+--------------------------------------------------------------------+ +| /:int | /([0-9]+) | Matches an integer parameter | ++--------------+---------------------+--------------------------------------------------------------------+ + +Controller names are camelized, this means that characters (-) and (_) are removed and the next character +is uppercased. For instance, some_controller is converted to SomeController. Since you can add many routes as you need using add(), the order in which you add the routes indicates their relevance, last routes added have more relevance than first added. Internally, all defined routes @@ -217,6 +224,23 @@ The following examples produce the same result: ) ); +Mixing Array and Short Syntax +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Array and short syntax can be mixed to define a route, in this case note that named parameters automatically +are added to the route paths according to the position on which they were defined: + +.. code-block:: php + + add('/news/{country:[a-z]{2}}/([a-z+])/([a-z\-+])', + array( + 'section' => 2, //Positions start with 2 + 'article' => 3 + ) + ); Routing to Modules ^^^^^^^^^^^^^^^^^^ @@ -267,6 +291,29 @@ Or you can bind specific routes to specific modules: 'action' => 1, )); +Or bind them to specific namespaces: + +.. code-block:: php + + add("/:namespace/login", array( + 'namespace' => 1, + 'controller' => 'login', + 'action' => 'index' + )); + +A controller can also be a full class name: + +.. code-block:: php + + add("/login", array( + 'controller' => 'Backend\Controllers\Login', + 'action' => 'index' + )); + HTTP Method Restrictions ^^^^^^^^^^^^^^^^^^^^^^^^ When you add a route using simply add(), the route will be enabled for any HTTP method. Sometimes we can restrict a route to a specific method, @@ -428,6 +475,11 @@ The following are examples of custom routes: "Feed::get" ); +.. highlights:: + Beware of characters allowed in regular expression for controllers and namespaces. As these + become class names and in turn pass through the file system could be used by attackers to + read unauthorized files. A safe regular expression is: /([a-zA-Z0-9\_\-]+) + Default Behavior ---------------- :doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` has a default behavior providing a very simple routing that @@ -471,7 +523,51 @@ those paths the component could automatically fill it: "action" => "index" )); -.. _PCRE regular expressions: http://www.php.net/manual/en/book.pcre.php +Testing your routes +------------------- +Since this component has no dependencies, you can create a file as shown below to test your routes: + +.. code-block:: php + + handle($testRoute); + + echo 'Testing ', $testRoute, '
'; + + //Check if some route was matched + if ($router->wasMatched()) { + echo 'Controller: ', $router->getControllerName(), '
'; + echo 'Action: ', $router->getActionName(), '
'; + } else { + echo 'The route wasn\'t matched by any route
'; + } + echo '
'; + + } + +Implementing your own Router +---------------------------- +The :doc:`Phalcon\\Mvc\\RouterInterface <../api/Phalcon_Mvc_RouterInterface>` interface must be implemented to create your own router replacing the one providing by Phalcon. + +.. _PCRE regular expressions: http://www.php.net/manual/en/book.pcre.php diff --git a/en/reference/session.rst b/en/reference/session.rst index a2c7ecd7ec06..23c1cb50aa79 100644 --- a/en/reference/session.rst +++ b/en/reference/session.rst @@ -13,7 +13,7 @@ Thanks to the service container, we can ensure that the session is accessed only set('session', function(){ + $di->setShared('session', function(){ $session = new Phalcon\Session\Adapter\Files(); $session->start(); return $session; @@ -169,3 +169,117 @@ In a component: The data added to the session ($this->session) are available throughout the application, while persistent ($this->persistent) can only be accessed in the scope of the current class. + +Implementing your own adapters +------------------------------ +The :doc:`Phalcon\\Session\\AdapterInterface <../api/Phalcon_Session_AdapterInterface>` interface must be implemented in order to create your own translate adapters or extend the existing ones: + +.. code-block:: php + + Inactive +You can add an "empty" option to the generated HTML: + +.. code-block:: php + + array("id", "name") + ), + 'useEmpty' => true + ); + +.. code-block:: html + + + +.. code-block:: php + + array("id", "name") + ), + 'useEmpty' => true, + 'emptyText' => 'Please, choose one...', + 'emptyValue' => '@' + ); + +.. code-block:: html + + + Assigning HTML attributes ------------------------- All the helpers accept an array as their first parameter which can contain additional HTML attributes for the element generated. diff --git a/en/reference/translate.rst b/en/reference/translate.rst index f63fb5948633..12544d03187b 100755 --- a/en/reference/translate.rst +++ b/en/reference/translate.rst @@ -116,3 +116,50 @@ are in the form of a key/value array, where the key matches the placeholder name Some applications implement multilingual on the URL such as http://www.mozilla.org/**es-ES**/firefox/. Phalcon can implement this by using a :doc:`Router `. +Implementing your own adapters +------------------------------ +The :doc:`Phalcon\\Translate\\AdapterInterface <../api/Phalcon_Translate_AdapterInterface>` interface must be implemented in order to create your own translate adapters or extend the existing ones: + +.. code-block:: php + + get("products/save"); + +Implementing your own Url Generator +----------------------------------- +The :doc:`Phalcon\\Mvc\\UrlInterface <../api/Phalcon_Mvc_UrlInterface>` interface must be implemented to create your own URL generator replacing the one providing by Phalcon. diff --git a/en/reference/views.rst b/en/reference/views.rst index 35a9ea44d0c2..0c39a8cbff38 100755 --- a/en/reference/views.rst +++ b/en/reference/views.rst @@ -398,10 +398,12 @@ the view rendered is the one related with the last controller and action execute Caching View Fragments ---------------------- -Sometimes when you develop dynamic websites and some areas of them are not updated very often, the output is exactly the same between requests. :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` offers caching a part or the whole rendered output to increase performance. +Sometimes when you develop dynamic websites and some areas of them are not updated very often, the output is exactly +the same between requests. :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` offers caching a part or the whole +rendered output to increase performance. -:doc:`Phalcon\\\Mvc\\View <../api/Phalcon_Mvc_View>` integrates with :doc:`Phalcon\\Cache ` to provide an easier way to cache output fragments. -You could manually set the cache handler or set a global handler: +:doc:`Phalcon\\\Mvc\\View <../api/Phalcon_Mvc_View>` integrates with :doc:`Phalcon\\Cache ` to provide an easier way +to cache output fragments. You could manually set the cache handler or set a global handler: .. code-block:: php @@ -419,7 +421,9 @@ You could manually set the cache handler or set a global handler: public function showArticleAction() { // Cache this view for 1 hour - $this->view->cache(array("lifetime" => 3600)); + $this->view->cache(array( + "lifetime" => 3600 + )); } public function resumeAction() @@ -433,10 +437,25 @@ You could manually set the cache handler or set a global handler: ); } + public function downloadAction() + { + //Passing a custom service + $this->view->cache( + array( + "service" => "myCache", + "lifetime" => 86400, + "key" => "resume-cache", + ) + ); + } + } -When the View component needs to cache something it will request a cache service to the services container. The service name convention for this -service is "viewCache": +When we do not define a key to the cache, the component automatically creates one doing a md5_ to view name currently rendered. +It is a good practice to define a key for each action so you can easily identify the cache associated with each view. + +When the View component needs to cache something it will request a cache service to the services container. +The service name convention for this service is "viewCache": .. code-block:: php @@ -457,7 +476,35 @@ service is "viewCache": )); return $cache; - }); + }, true); + +When using view caching is also useful to prevent that controllers perform the processes that produce the data to be displayed in the views. + +To achieve this we must identify uniquely each cache with a key. First we verify that the cache does not exist or has expired to make the +calculations/queries to display data in the view: + +view->getCache()->exists('downloads')) { + + //Query the latest downloads + $latest = Downloads::find(array('order' => 'created_at DESC')); + + $this->view->setVar('latest', $latest); + } + + //Enable the cache with the same key "downloads" + $this->view->cache(array('key' => 'downloads')); + } + +} Disabling the view ------------------ @@ -666,7 +713,7 @@ template engine, you can register it in the initialize() method of the controlle set('view', function(){ + $di->set('view', function() { //Create an event manager $eventsManager = new Phalcon\Events\Manager(); @@ -957,7 +1005,8 @@ The following example shows how to create a plugin that clean/repair the HTML pr class TidyPlugin { - public function afterRender($event, $view){ + public function afterRender($event, $view) + { $tidyConfig = array( 'clean' => true, @@ -982,4 +1031,5 @@ The following example shows how to create a plugin that clean/repair the HTML pr .. _this Github repository: https://github.com/bobthecow/mustache.php .. _ajax request: http://api.jquery.com/jQuery.ajax/ .. _Smarty: http://www.smarty.net/ -.. _Tidy: http://www.php.net/manual/en/book.tidy.php \ No newline at end of file +.. _Tidy: http://www.php.net/manual/en/book.tidy.php +.. _md5: http://php.net/manual/en/function.md5.php \ No newline at end of file diff --git a/en/reference/volt.rst b/en/reference/volt.rst index a423b0b29af5..9b1806dd27f3 100644 --- a/en/reference/volt.rst +++ b/en/reference/volt.rst @@ -5,6 +5,9 @@ Volt is an ultra-fast and designer friendly templating language written in C for helpers to write views in an easy way. Volt is highly integrated with other components of Phalcon, just as you can use it as a stand-alone component in your applications. +.. figure:: ../_static/img/volt.jpg + :align: center + Volt is inspired on Twig_, originally created by Armin Ronacher, which in turn is inspired in Jinja_. Therefore many developers will be in familiar ground using the same syntax they have been using with Twig. Volt’s syntax and features have been enhanced with more elements and of course @@ -527,6 +530,14 @@ Not all blocks must be replaced at a child template, only those which are needed +As partials, the path set to "extends" is a relative path under the current directory for views (i.e app/views/). + +.. highlights:: + + By default, and for performance reasons, Volt only checks for changes in the children templates, + so it is recommended initialize Volt with the option 'compileAlways' => true. Thus, the templates + are compiled always taking into account changes in the parent templates. + Setting up the Volt Engine -------------------------- Volt can be configured to alter its default behavior, the following example explain how to do that: @@ -538,7 +549,7 @@ Volt can be configured to alter its default behavior, the following example expl //Register Volt as a service $di->set('voltService', function($view, $di) { - $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); + $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); $volt->setOptions(array( "compiledPath" => "../app/compiled-templates/", @@ -562,6 +573,33 @@ Volt can be configured to alter its default behavior, the following example expl return $view; }); +If you do not want to reuse Volt as a service you can pass an anonymous function to register the engine instead of a service name: + +.. code-block:: php + + set('view', function() { + + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines(array( + ".volt" => function($view, $di) { + $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di); + + //set some options here + + return $volt; + } + )); + + return $view; + }); + + The following options are available in Volt: +-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ @@ -575,7 +613,14 @@ The following options are available in Volt: +-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ | stat | Whether Phalcon must check if exists differences between the template file and its compiled path | true | +-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ +| compileAlways | Tell Volt if the templates must be compiled in each request or only when they change | false | ++-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ + +External Resources +------------------ +* A bundle for Sublime/Textmate is available `here `_ +* Our website is running using Volt as template engine, check out its code on `github `_ .. _Twig: https://github.com/vito/chyrp/wiki/Twig-Reference .. _Jinja: http://jinja.pocoo.org/ diff --git a/scripts/gen-api.php b/scripts/gen-api.php index 8a77f2b3a3f1..e26f33c33b49 100644 --- a/scripts/gen-api.php +++ b/scripts/gen-api.php @@ -8,7 +8,7 @@ * php scripts/gen-api.php */ -define('CPHALCON_DIR', '/Users/kenjikobe/cphalcon/ext/'); +define('CPHALCON_DIR', '/Users/gutierrezandresfelipe/cphalcon/ext/'); class API_Generator { diff --git a/zh/Makefile b/zh/Makefile new file mode 100755 index 000000000000..8bc42ee9baab --- /dev/null +++ b/zh/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PhalconDocumentation.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PhalconDocumentation.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/PhalconDocumentation" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PhalconDocumentation" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/zh/_static/background.png b/zh/_static/background.png new file mode 100644 index 000000000000..db948e7dedf5 Binary files /dev/null and b/zh/_static/background.png differ diff --git a/zh/_static/docs.css b/zh/_static/docs.css new file mode 100755 index 000000000000..e89754aab9ee --- /dev/null +++ b/zh/_static/docs.css @@ -0,0 +1,467 @@ +html { + background: none; +} + +body { + color: #333333; + font-family: "Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif; + font-size: 14px; + line-height: 22px; + margin: 0 0 11px; +} + +#nav-main { + background-color: #2C2C2C; + background-image: -moz-linear-gradient(center top , #333333, #222222); +} + +h2 { + font-family: "Open Sans",sans-serif; + font-style: normal; + letter-spacing: normal; + color: #333333; + font-size: 20px; + line-height: 24px; + font-weight: 500; + margin: 25px 0 0; +} + +/*p, li { + color: #434343; +}*/ + +td.primary-box li { + padding: 0px; + line-height: 16px; + margin-bottom: 0px; + font-size: 14px; +} + +td.second-box li { + margin-bottom: 0em; +} + +td.second-box li.toctree-l1 { + font-size: 14px; + margin: 0px; +} + +td.second-box li.toctree-l1 a { + font-size: 14px; + margin-bottom: 0em; +} + +td.primary-box { + padding: 10px; + padding-right: 20px; + padding-top: 15px; + text-align: left; +} + +td.primary-box ul { + margin-left: 0px; + padding-left: 5px; +} + +td.primary-box li { + margin-left: 0px; + padding-left: 5px; +} + +td.primary-box a { + color: #0088CC; + font-size: 13px; + line-height: 20px; + text-decoration: none; +} + +td.second-box { + padding: 30px 15px 10px 10px; + max-width: 650px; + text-align: left; +} + +div.documentwrapper h1 { + color: #000000; + display: block; + /*font: italic 36px Georgia,"Times New Roman",Times,serif; + letter-spacing: -3px; + text-rendering: optimizelegibility;*/ + font: 400 30px/44px 'Open Sans','Lucida Sans Unicode','Lucida Grande',sans-serif; + margin: 0; +} + +div.section { + margin-top: 10px; +} + +a.headerlink { + color: #dadada; + font-size: 18px; + margin-left: 10px; +} + +div.related { + padding-top: 10px; + padding-bottom: 10px; + width: 95%; +} + +div.related li { + float: left; + padding-right: 20px; + list-style: none outside none; +} + +div.related a { + font-size: 13px; +} + +div.related li.right { + float: right; + padding-right: 0px; + list-style: none outside none; + color: white; + margin-right: 5px; +} + +div.related li.right a { + background: none repeat scroll 0 0 #0088CC; + padding: 10px; + border-radius: 5px; + color: #fff; +} + +.align-center { + text-align: center; +} + +p.versionadded { + background: none repeat scroll 0 0 #A8CEBB; + font-size: 15px; + margin-left: 20px; + margin-right: 20px; + padding: 5px; +} + +p.versionchanged, +blockquote.highlights { + color: #414141; + font-family: "Open Sans",sans-serif; + background: none repeat scroll 0 0 #D5E9F6; + line-height: 24px; + padding: 10px; + text-align: left; + text-rendering: optimizelegibility; + font-size: 15px; + margin-left: 20px; + margin-right: 20px; + margin-top: 10px; +} + +blockquote.highlights { + padding: 10px; +} + +span.versionmodified { + font-style: italic; +} + +/*div.highlight { + background: none repeat scroll 0 0 #212121; + margin: 7px 5px 5px; + max-width: 95%; + overflow-x: scroll; + text-align: left; + margin-left: 0px; +} + +div.highlight, +blockquote { + background: none repeat scroll 0 0 #212121; + font-family: Consolas,"Lucida Console",monospace; + font-size: 14px; + line-height: 18px; + color: #DCDCCC; + margin: 0 0 0 15px; + padding: 2px; +} + +div.highlight span, +blockquote span { + font-family: Consolas,"Lucida Console",monospace; + font-size: 14px; + line-height: 18px; +} + +blockquote { + padding: 3px; +} + +blockquote p { + font-size: 14px; + line-height: 18px; + color: #DCDCCC; +}*/ + +p.topless { + margin: 0px; + padding: 0px; +} + +div.figure { + padding: 10px; +} + +.highlight .cp { + color: #DCDCCC; +} + +.highlight .nb { + color: #EFDCBC; +} + +.highlight .k { + color: #F0DFAF; + font-weight: bold; +} + +.highlight .c1, +.highlight .cm { + color: #7F9F7F; + font-style: italic; +} + +.highlight .nx { + color: #FAFAFA; +} + +.highlight .na { + color: #EFDCBC; +} + +.highlight .s, +.highlight .s1, +.highlight .s2, +.highlight .sb { + color: #CC9393; +} + +.highlight .nv { + color: #EFDCBC; +} + +.highlight .o { + color: #DCDCCC; +} + +.highlight .nc { + color: #fafafa; + font-weight: bold; +} + +.highlight .nf { + color: #fafafa; + font-weight: bold; +} + +.highlight .mi, +.highlight .mf, +.highlight .m { + color: #8CD0D3; +} + +.highlight .nt { + color: #919191; +} + +.highlight .sd { + color: #7F9F7F; + font-style: italic; +} + +.highlight .se { + color: #ababab; + font-weight: bold; +} + +.highlight .kn { + color: #FAFAFA; + font-weight: bold; +} + +.highlight .sr { + color: #DADADA; +} + +.highlight .si { + color: #EFDCBC; + font-style: italic; +} + +.highlight .kd { + color: #dadada; +} + +table.docutils { + border-collapse: collapse; + border-top: 1px solid #DDDDDD; + border-left: 1px solid #DDDDDD; + margin-left: auto; + margin-right: auto; + width: 95%; + margin-bottom: 15px; + border-radius: 4px; +} + +table.docutils td, +table.docutils th { + color: #434343; + border-bottom: 1px solid #DDDDDD; + border-right: 1px solid #DDDDDD; + padding: 5px; +} + +table.docutils th { + background: none repeat scroll 0 0 #F9F9F9; + text-align: center; +} + +table.docutils tr { + padding: 0px; + margin: 0px; +} + +div#methods h2, +div#constants h2 { + color: #999999; +} + +div#methods a, +div#constants a, { + text-decoration: none; +} + +div#methods a:hover { + text-decoration: underline; +} + +div#methods em, +div#constants em { + color: #0088CC; +} + +p.method-desc { + margin-left: 25px; + font-size: 14px; + margin-bottom: 20px; + margin-top: 10px; +} + +div#methods span.modifier { + color: #267B0C; +} + +div#methods span.inherited { + color: #999999; + font-style: italic; +} + +em { + font-style: normal; +} + +p.versionchanged, blockquote.highlights { + background-color: #D9EDF7; + border-color: #BCE8F1; + color: #3A87AD; +} + +div#footer { + padding: 50px 10px; + background: none repeat scroll 0 0 #0088CC; +} + +div.highlight, blockquote { + font-family: Monaco,Menlo,Consolas,"Courier New",monospace; + background-color: #F5F5F5; + border: 1px solid rgba(0, 0, 0, 0.15); + border-radius: 4px 4px 4px 4px; + display: block; + font-size: 13px; + line-height: 17px; + margin: 0 0 11px; + padding: 5px; + padding-left: 10px; + word-wrap: break-word; +} + +div.highlight { + word-break: break-all; +} + +.highlight .sd { + color: #93A1A1; + font-weight: normal; +} + +.highlight .k { + color: #1E347B; + font-weight: normal; +} + +.highlight .nf, +.highlight .nc { + color: #48484C; + font-weight: normal; +} + +.highlight .nv { + color: #48484C; +} + +.highlight .nx, +.highlight .na, +.highlight .nb { + color: teal; +} + +.highlight .s, .highlight .s1, .highlight .s2, .highlight .sb { + color: #DD1144; +} + +.highlight .c1, .highlight .cm { + color: #93A1A1; + font-style: italic; +} + +.highlight .o { + color: #1E347B; +} + +.highlight .cp { + color: rgba(0, 0, 0, 0.4); +} + +.highlight .nt { + color: #1E347B; + font-weight: normal; +} + +.highlight .si { + color: coral; + font-weight: normal; +} + +.highlight .mi, .highlight .mf, .highlight .m { + color: teal; +} + +.highlight .ni { + color: teal; + font-weight: bold; +} + +pre { + font-family: Monaco,Menlo,Consolas,"Courier New",monospace; +} \ No newline at end of file diff --git a/zh/_static/docs.js b/zh/_static/docs.js new file mode 100644 index 000000000000..eb839dd89a6e --- /dev/null +++ b/zh/_static/docs.js @@ -0,0 +1,22 @@ + +$(document).ready(function() { + $("#versions").change(function() { + var docsUrl = $(this).val(); + window.location.href = docsUrl; + }); + var n = 1; + $("div#methods p").each(function() { + if (n%2 == 0) { + $(this).addClass("method-desc"); + } else { + var text = this.innerHTML; + text = text.replace("public ", "public "); + text = text.replace("protected ", "protected "); + text = text.replace("final ", "final "); + text = text.replace("static ", "static "); + text = text.replace("inherited from", "inherited from "); + this.innerHTML = text; + }; + n++; + }); +}); \ No newline at end of file diff --git a/zh/_static/favicon.ico b/zh/_static/favicon.ico new file mode 100755 index 000000000000..b08b013581d6 Binary files /dev/null and b/zh/_static/favicon.ico differ diff --git a/zh/_static/img/background.png b/zh/_static/img/background.png new file mode 100644 index 000000000000..db948e7dedf5 Binary files /dev/null and b/zh/_static/img/background.png differ diff --git a/zh/_static/img/bench-1.png b/zh/_static/img/bench-1.png new file mode 100755 index 000000000000..582665ceed76 Binary files /dev/null and b/zh/_static/img/bench-1.png differ diff --git a/zh/_static/img/bench-2.png b/zh/_static/img/bench-2.png new file mode 100755 index 000000000000..36df8d613c6f Binary files /dev/null and b/zh/_static/img/bench-2.png differ diff --git a/zh/_static/img/bench-3.png b/zh/_static/img/bench-3.png new file mode 100755 index 000000000000..49e5db3709ab Binary files /dev/null and b/zh/_static/img/bench-3.png differ diff --git a/zh/_static/img/bench-4.png b/zh/_static/img/bench-4.png new file mode 100644 index 000000000000..8bab5fd6acb3 Binary files /dev/null and b/zh/_static/img/bench-4.png differ diff --git a/zh/_static/img/bench-5.png b/zh/_static/img/bench-5.png new file mode 100644 index 000000000000..884ad71b6bb0 Binary files /dev/null and b/zh/_static/img/bench-5.png differ diff --git a/zh/_static/img/invo-1.png b/zh/_static/img/invo-1.png new file mode 100644 index 000000000000..3e4409251b85 Binary files /dev/null and b/zh/_static/img/invo-1.png differ diff --git a/zh/_static/img/invo-2.png b/zh/_static/img/invo-2.png new file mode 100644 index 000000000000..9a7f45268af0 Binary files /dev/null and b/zh/_static/img/invo-2.png differ diff --git a/zh/_static/img/linux-1.png b/zh/_static/img/linux-1.png new file mode 100644 index 000000000000..42eaadc62365 Binary files /dev/null and b/zh/_static/img/linux-1.png differ diff --git a/zh/_static/img/linux-2.png b/zh/_static/img/linux-2.png new file mode 100644 index 000000000000..1c38f60592ae Binary files /dev/null and b/zh/_static/img/linux-2.png differ diff --git a/zh/_static/img/logo-small.png b/zh/_static/img/logo-small.png new file mode 100644 index 000000000000..6ea6508188c6 Binary files /dev/null and b/zh/_static/img/logo-small.png differ diff --git a/zh/_static/img/mac-1.png b/zh/_static/img/mac-1.png new file mode 100644 index 000000000000..4444e2689d9b Binary files /dev/null and b/zh/_static/img/mac-1.png differ diff --git a/zh/_static/img/mac-2.png b/zh/_static/img/mac-2.png new file mode 100644 index 000000000000..13170540b2dd Binary files /dev/null and b/zh/_static/img/mac-2.png differ diff --git a/zh/_static/img/mac-3.png b/zh/_static/img/mac-3.png new file mode 100644 index 000000000000..c6a31b1dc3f8 Binary files /dev/null and b/zh/_static/img/mac-3.png differ diff --git a/zh/_static/img/mac-4.png b/zh/_static/img/mac-4.png new file mode 100644 index 000000000000..ccc088e54547 Binary files /dev/null and b/zh/_static/img/mac-4.png differ diff --git a/zh/_static/img/mac-5.png b/zh/_static/img/mac-5.png new file mode 100644 index 000000000000..c1cfa90e09fa Binary files /dev/null and b/zh/_static/img/mac-5.png differ diff --git a/zh/_static/img/migrations-1.png b/zh/_static/img/migrations-1.png new file mode 100755 index 000000000000..2e6d37c28fdf Binary files /dev/null and b/zh/_static/img/migrations-1.png differ diff --git a/zh/_static/img/migrations-2.png b/zh/_static/img/migrations-2.png new file mode 100755 index 000000000000..016edca91778 Binary files /dev/null and b/zh/_static/img/migrations-2.png differ diff --git a/zh/_static/img/migrations-3.png b/zh/_static/img/migrations-3.png new file mode 100755 index 000000000000..77df5563af46 Binary files /dev/null and b/zh/_static/img/migrations-3.png differ diff --git a/zh/_static/img/migrations-4.png b/zh/_static/img/migrations-4.png new file mode 100755 index 000000000000..bbc9d7046ba2 Binary files /dev/null and b/zh/_static/img/migrations-4.png differ diff --git a/zh/_static/img/migrations-5.png b/zh/_static/img/migrations-5.png new file mode 100755 index 000000000000..3d05160e133b Binary files /dev/null and b/zh/_static/img/migrations-5.png differ diff --git a/zh/_static/img/path-0.png b/zh/_static/img/path-0.png new file mode 100644 index 000000000000..8ba128cbc480 Binary files /dev/null and b/zh/_static/img/path-0.png differ diff --git a/zh/_static/img/path-01.png b/zh/_static/img/path-01.png new file mode 100644 index 000000000000..ba0ef8d09149 Binary files /dev/null and b/zh/_static/img/path-01.png differ diff --git a/zh/_static/img/path-1.png b/zh/_static/img/path-1.png new file mode 100644 index 000000000000..18d601539d6b Binary files /dev/null and b/zh/_static/img/path-1.png differ diff --git a/zh/_static/img/path-2.png b/zh/_static/img/path-2.png new file mode 100644 index 000000000000..5f1fdcc489aa Binary files /dev/null and b/zh/_static/img/path-2.png differ diff --git a/zh/_static/img/path-3.png b/zh/_static/img/path-3.png new file mode 100644 index 000000000000..f82204558e47 Binary files /dev/null and b/zh/_static/img/path-3.png differ diff --git a/zh/_static/img/path-4.png b/zh/_static/img/path-4.png new file mode 100644 index 000000000000..d065c2228151 Binary files /dev/null and b/zh/_static/img/path-4.png differ diff --git a/zh/_static/img/path-5.png b/zh/_static/img/path-5.png new file mode 100644 index 000000000000..2664a8b7a5ff Binary files /dev/null and b/zh/_static/img/path-5.png differ diff --git a/zh/_static/img/path-6.png b/zh/_static/img/path-6.png new file mode 100644 index 000000000000..ddf38f9a4041 Binary files /dev/null and b/zh/_static/img/path-6.png differ diff --git a/zh/_static/img/path-7.png b/zh/_static/img/path-7.png new file mode 100644 index 000000000000..95e39552dee0 Binary files /dev/null and b/zh/_static/img/path-7.png differ diff --git a/zh/_static/img/sql.png b/zh/_static/img/sql.png new file mode 100755 index 000000000000..2cccbd3d2ca8 Binary files /dev/null and b/zh/_static/img/sql.png differ diff --git a/zh/_static/img/tools-1.png b/zh/_static/img/tools-1.png new file mode 100755 index 000000000000..c9833feb5583 Binary files /dev/null and b/zh/_static/img/tools-1.png differ diff --git a/zh/_static/img/tools-10.png b/zh/_static/img/tools-10.png new file mode 100755 index 000000000000..631081bc94fe Binary files /dev/null and b/zh/_static/img/tools-10.png differ diff --git a/zh/_static/img/tools-11.png b/zh/_static/img/tools-11.png new file mode 100755 index 000000000000..305321fefe8e Binary files /dev/null and b/zh/_static/img/tools-11.png differ diff --git a/zh/_static/img/tools-12.png b/zh/_static/img/tools-12.png new file mode 100755 index 000000000000..5bf302f1335c Binary files /dev/null and b/zh/_static/img/tools-12.png differ diff --git a/zh/_static/img/tools-13.png b/zh/_static/img/tools-13.png new file mode 100755 index 000000000000..085c98f7d4e0 Binary files /dev/null and b/zh/_static/img/tools-13.png differ diff --git a/zh/_static/img/tools-2.png b/zh/_static/img/tools-2.png new file mode 100755 index 000000000000..6d51dde7ae6b Binary files /dev/null and b/zh/_static/img/tools-2.png differ diff --git a/zh/_static/img/tools-3.png b/zh/_static/img/tools-3.png new file mode 100755 index 000000000000..b28490bc96cc Binary files /dev/null and b/zh/_static/img/tools-3.png differ diff --git a/zh/_static/img/tools-4.png b/zh/_static/img/tools-4.png new file mode 100755 index 000000000000..cd3840696fc1 Binary files /dev/null and b/zh/_static/img/tools-4.png differ diff --git a/zh/_static/img/tools-5.png b/zh/_static/img/tools-5.png new file mode 100755 index 000000000000..10cc608d8be6 Binary files /dev/null and b/zh/_static/img/tools-5.png differ diff --git a/zh/_static/img/tools-6.png b/zh/_static/img/tools-6.png new file mode 100755 index 000000000000..9f30d8d27b40 Binary files /dev/null and b/zh/_static/img/tools-6.png differ diff --git a/zh/_static/img/tools-7.png b/zh/_static/img/tools-7.png new file mode 100755 index 000000000000..658cd2d8b3fc Binary files /dev/null and b/zh/_static/img/tools-7.png differ diff --git a/zh/_static/img/tools-8.png b/zh/_static/img/tools-8.png new file mode 100755 index 000000000000..00c7b8d66f71 Binary files /dev/null and b/zh/_static/img/tools-8.png differ diff --git a/zh/_static/img/tools-9.png b/zh/_static/img/tools-9.png new file mode 100755 index 000000000000..09d5fbc53d0b Binary files /dev/null and b/zh/_static/img/tools-9.png differ diff --git a/zh/_static/img/tutorial-1.png b/zh/_static/img/tutorial-1.png new file mode 100755 index 000000000000..59a29ff77e6c Binary files /dev/null and b/zh/_static/img/tutorial-1.png differ diff --git a/zh/_static/img/tutorial-2.png b/zh/_static/img/tutorial-2.png new file mode 100755 index 000000000000..fc99be12874e Binary files /dev/null and b/zh/_static/img/tutorial-2.png differ diff --git a/zh/_static/img/tutorial-3.png b/zh/_static/img/tutorial-3.png new file mode 100755 index 000000000000..cb79c5399494 Binary files /dev/null and b/zh/_static/img/tutorial-3.png differ diff --git a/zh/_static/img/tutorial-4.png b/zh/_static/img/tutorial-4.png new file mode 100755 index 000000000000..ef213a895830 Binary files /dev/null and b/zh/_static/img/tutorial-4.png differ diff --git a/zh/_static/img/views-1.png b/zh/_static/img/views-1.png new file mode 100755 index 000000000000..be34f6f5eef7 Binary files /dev/null and b/zh/_static/img/views-1.png differ diff --git a/zh/_static/img/wamp-1.png b/zh/_static/img/wamp-1.png new file mode 100755 index 000000000000..18cfcc4feead Binary files /dev/null and b/zh/_static/img/wamp-1.png differ diff --git a/zh/_static/img/wamp-2.png b/zh/_static/img/wamp-2.png new file mode 100755 index 000000000000..d11829169cb1 Binary files /dev/null and b/zh/_static/img/wamp-2.png differ diff --git a/zh/_static/img/wamp-3.png b/zh/_static/img/wamp-3.png new file mode 100755 index 000000000000..ad0cfe3c0313 Binary files /dev/null and b/zh/_static/img/wamp-3.png differ diff --git a/zh/_static/img/wamp-4.png b/zh/_static/img/wamp-4.png new file mode 100755 index 000000000000..7415d3dfd4c1 Binary files /dev/null and b/zh/_static/img/wamp-4.png differ diff --git a/zh/_static/img/xampp-1.png b/zh/_static/img/xampp-1.png new file mode 100755 index 000000000000..44d749190236 Binary files /dev/null and b/zh/_static/img/xampp-1.png differ diff --git a/zh/_static/img/xampp-2.png b/zh/_static/img/xampp-2.png new file mode 100755 index 000000000000..1f4b878445ce Binary files /dev/null and b/zh/_static/img/xampp-2.png differ diff --git a/zh/_static/img/xampp-3.png b/zh/_static/img/xampp-3.png new file mode 100755 index 000000000000..79c44b0a6834 Binary files /dev/null and b/zh/_static/img/xampp-3.png differ diff --git a/zh/_static/img/xampp-4.png b/zh/_static/img/xampp-4.png new file mode 100755 index 000000000000..197e3d18e3d6 Binary files /dev/null and b/zh/_static/img/xampp-4.png differ diff --git a/zh/_static/img/xampp-5.png b/zh/_static/img/xampp-5.png new file mode 100755 index 000000000000..ba3c5edd7f8a Binary files /dev/null and b/zh/_static/img/xampp-5.png differ diff --git a/zh/_static/img/xampp-6.png b/zh/_static/img/xampp-6.png new file mode 100755 index 000000000000..00223946f563 Binary files /dev/null and b/zh/_static/img/xampp-6.png differ diff --git a/zh/_static/img/xampp-7.png b/zh/_static/img/xampp-7.png new file mode 100755 index 000000000000..d2ff76738835 Binary files /dev/null and b/zh/_static/img/xampp-7.png differ diff --git a/zh/_static/jquery.js b/zh/_static/jquery.js new file mode 100644 index 000000000000..e7f2a292bd33 --- /dev/null +++ b/zh/_static/jquery.js @@ -0,0 +1,2 @@ +/*! jQuery v@1.8.1 jquery.com | jquery.org/license */ +(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write(""),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.1",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b
a",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="
t
",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="
",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j=0),h[l]&&j.push(k);j.length&&t.push({elem:f,matches:j})}n.length>o&&t.push({elem:this,matches:n.slice(o)});for(d=0;d0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function $(a,b,c,d){c=c||[],b=b||q;var e,f,g,j,k=b.nodeType;if(k!==1&&k!==9)return[];if(!a||typeof a!="string")return c;g=h(b);if(!g&&!d)if(e=L.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&i(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return u.apply(c,t.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&X&&b.getElementsByClassName)return u.apply(c,t.call(b.getElementsByClassName(j),0)),c}return bk(a,b,c,d,g)}function _(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function ba(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bb(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bc(a,b,c,d){var e,g,h,i,j,k,l,m,n,p,r=!c&&b!==q,s=(r?"":"")+a.replace(H,"$1"),u=y[o][s];if(u)return d?0:t.call(u,0);j=a,k=[],m=0,n=f.preFilter,p=f.filter;while(j){if(!e||(g=I.exec(j)))g&&(j=j.slice(g[0].length),h.selector=l),k.push(h=[]),l="",r&&(j=" "+j);e=!1;if(g=J.exec(j))l+=g[0],j=j.slice(g[0].length),e=h.push({part:g.pop().replace(H," "),string:g[0],captures:g});for(i in p)(g=S[i].exec(j))&&(!n[i]||(g=n[i](g,b,c)))&&(l+=g[0],j=j.slice(g[0].length),e=h.push({part:i,string:g.shift(),captures:g}));if(!e)break}return l&&(h.selector=l),d?j.length:j?$.error(a):t.call(y(s,k),0)}function bd(a,b,e,f){var g=b.dir,h=s++;return a||(a=function(a){return a===e}),b.first?function(b){while(b=b[g])if(b.nodeType===1)return a(b)&&b}:f?function(b){while(b=b[g])if(b.nodeType===1&&a(b))return b}:function(b){var e,f=h+"."+c,i=f+"."+d;while(b=b[g])if(b.nodeType===1){if((e=b[o])===i)return b.sizset;if(typeof e=="string"&&e.indexOf(f)===0){if(b.sizset)return b}else{b[o]=i;if(a(b))return b.sizset=!0,b;b.sizset=!1}}}}function be(a,b){return a?function(c){var d=b(c);return d&&a(d===!0?c:d)}:b}function bf(a,b,c){var d,e,g=0;for(;d=a[g];g++)f.relative[d.part]?e=bd(e,f.relative[d.part],b,c):e=be(e,f.filter[d.part].apply(null,d.captures.concat(b,c)));return e}function bg(a){return function(b){var c,d=0;for(;c=a[d];d++)if(c(b))return!0;return!1}}function bh(a,b,c,d){var e=0,f=b.length;for(;e0?i(h,c,g):[]}function bj(a,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q,r,s=0,t=a.length,v=S.POS,w=new RegExp("^"+v.source+"(?!"+A+")","i"),x=function(){var a=1,c=arguments.length-2;for(;al){g+=k.slice(l,n.index),l=p,q=[c],J.test(g)&&(m&&(q=m),m=e);if(r=O.test(g))g=g.slice(0,-5).replace(J,"$&*"),l++;n.length>1&&n[0].replace(w,x),m=bi(g,n[1],n[2],q,m,r)}g=""}}o||(g+=k),o=!1}g?J.test(g)?bh(g,m||[c],d,e):$(g,c,d,e?e.concat(m):m):u.apply(d,m)}return t===1?d:$.uniqueSort(d)}function bk(a,b,e,g,h){a=a.replace(H,"$1");var i,k,l,m,n,o,p,q,r,s,v=bc(a,b,h),w=b.nodeType;if(S.POS.test(a))return bj(v,b,e,g);if(g)i=t.call(g,0);else if(v.length===1){if((o=t.call(v[0],0)).length>2&&(p=o[0]).part==="ID"&&w===9&&!h&&f.relative[o[1].part]){b=f.find.ID(p.captures[0].replace(R,""),b,h)[0];if(!b)return e;a=a.slice(o.shift().string.length)}r=(v=N.exec(o[0].string))&&!v.index&&b.parentNode||b,q="";for(n=o.length-1;n>=0;n--){p=o[n],s=p.part,q=p.string+q;if(f.relative[s])break;if(f.order.test(s)){i=f.find[s](p.captures[0].replace(R,""),r,h);if(i==null)continue;a=a.slice(0,a.length-q.length)+q.replace(S[s],""),a||u.apply(e,t.call(i,0));break}}}if(a){k=j(a,b,h),c=k.dirruns++,i==null&&(i=f.find.TAG("*",N.test(a)&&b.parentNode||b));for(n=0;m=i[n];n++)d=k.runs++,k(m)&&e.push(m)}return e}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=a.document,r=q.documentElement,s=0,t=[].slice,u=[].push,v=function(a,b){return a[o]=b||!0,a},w=function(){var a={},b=[];return v(function(c,d){return b.push(c)>f.cacheLength&&delete a[b.shift()],a[c]=d},a)},x=w(),y=w(),z=w(),A="[\\x20\\t\\r\\n\\f]",B="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",C=B.replace("w","w#"),D="([*^$|!~]?=)",E="\\["+A+"*("+B+")"+A+"*(?:"+D+A+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+C+")|)|)"+A+"*\\]",F=":("+B+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+E+")|[^:]|\\\\.)*|.*))\\)|)",G=":(nth|eq|gt|lt|first|last|even|odd)(?:\\(((?:-\\d)?\\d*)\\)|)(?=[^-]|$)",H=new RegExp("^"+A+"+|((?:^|[^\\\\])(?:\\\\.)*)"+A+"+$","g"),I=new RegExp("^"+A+"*,"+A+"*"),J=new RegExp("^"+A+"*([\\x20\\t\\r\\n\\f>+~])"+A+"*"),K=new RegExp(F),L=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,M=/^:not/,N=/[\x20\t\r\n\f]*[+~]/,O=/:not\($/,P=/h\d/i,Q=/input|select|textarea|button/i,R=/\\(?!\\)/g,S={ID:new RegExp("^#("+B+")"),CLASS:new RegExp("^\\.("+B+")"),NAME:new RegExp("^\\[name=['\"]?("+B+")['\"]?\\]"),TAG:new RegExp("^("+B.replace("w","w*")+")"),ATTR:new RegExp("^"+E),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+A+"*(even|odd|(([+-]|)(\\d*)n|)"+A+"*(?:([+-]|)"+A+"*(\\d+)|))"+A+"*\\)|)","i"),POS:new RegExp(G,"ig"),needsContext:new RegExp("^"+A+"*[>+~]|"+G,"i")},T=function(a){var b=q.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},U=T(function(a){return a.appendChild(q.createComment("")),!a.getElementsByTagName("*").length}),V=T(function(a){return a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),W=T(function(a){a.innerHTML="";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),X=T(function(a){return a.innerHTML="",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),Y=T(function(a){a.id=o+0,a.innerHTML="
",r.insertBefore(a,r.firstChild);var b=q.getElementsByName&&q.getElementsByName(o).length===2+q.getElementsByName(o+0).length;return e=!q.getElementById(o),r.removeChild(a),b});try{t.call(r.childNodes,0)[0].nodeType}catch(Z){t=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}$.matches=function(a,b){return $(a,null,null,b)},$.matchesSelector=function(a,b){return $(b,null,null,[a]).length>0},g=$.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=g(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=g(b);return c},h=$.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},i=$.contains=r.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:r.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},$.attr=function(a,b){var c,d=h(a);return d||(b=b.toLowerCase()),f.attrHandle[b]?f.attrHandle[b](a):W||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},f=$.selectors={cacheLength:50,createPseudo:v,match:S,order:new RegExp("ID|TAG"+(Y?"|NAME":"")+(X?"|CLASS":"")),attrHandle:V?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:e?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:U?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(R,""),a[3]=(a[4]||a[5]||"").replace(R,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||$.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&$.error(a[0]),a},PSEUDO:function(a,b,c){var d,e;if(S.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(d=a[4])K.test(d)&&(e=bc(d,b,c,!0))&&(e=d.indexOf(")",d.length-e)-d.length)&&(d=d.slice(0,e),a[0]=a[0].slice(0,e)),a[2]=d;return a.slice(0,3)}},filter:{ID:e?function(a){return a=a.replace(R,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(R,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(R,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=x[o][a];return b||(b=x(a,new RegExp("(^|"+A+")"+a+"("+A+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=$.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return $.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=s++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[o]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[o]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e,g=f.pseudos[a]||f.pseudos[a.toLowerCase()];return g||$.error("unsupported pseudo: "+a),g[o]?g(b,c,d):g.length>1?(e=[a,a,"",b],function(a){return g(a,0,e)}):g}},pseudos:{not:v(function(a,b,c){var d=j(a.replace(H,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!f.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:v(function(a){return function(b){return(b.textContent||b.innerText||g(b)).indexOf(a)>-1}}),has:v(function(a){return function(b){return $(a,b).length>0}}),header:function(a){return P.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:_("radio"),checkbox:_("checkbox"),file:_("file"),password:_("password"),image:_("image"),submit:ba("submit"),reset:ba("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return Q.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e",a.querySelectorAll("[selected]").length||e.push("\\["+A+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="

",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+A+"*(?:\"\"|'')"),a.innerHTML="",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bk=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return u.apply(f,t.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j,k,l,m=d.getAttribute("id"),n=m||o,p=N.test(a)&&d.parentNode||d;m?n=n.replace(c,"\\$&"):d.setAttribute("id",n),j=bc(a,d,h),n="[id='"+n+"']";for(k=0,l=j.length;k0})}(),f.setFilters.nth=f.setFilters.eq,f.filters=f.pseudos,$.attr=p.attr,p.find=$,p.expr=$.selectors,p.expr[":"]=p.expr.pseudos,p.unique=$.uniqueSort,p.text=$.getText,p.isXMLDoc=$.isXML,p.contains=$.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b0)for(e=d;e=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*\s*$/g,bz={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X
","
"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1>");try{for(;d1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]===""&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{cj=f.href}catch(cy){cj=e.createElement("a"),cj.href="",cj=cj.href}ck=ct.exec(cj.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("
").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:cj,isLocal:cn.test(ck[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,ck[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==ck[1]&&i[2]==ck[2]&&(i[3]||(i[1]==="http:"?80:443))==(ck[3]||(ck[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cQ.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); \ No newline at end of file diff --git a/zh/_static/s.css b/zh/_static/s.css new file mode 100644 index 000000000000..797f4beaab38 --- /dev/null +++ b/zh/_static/s.css @@ -0,0 +1 @@ +html{background:url("./img/background.png") repeat-x scroll 0 -730px #fff}body{color:#333;font-family:"Open Sans",sans-serif;font-size:13px;line-height:1.231;border-top:2px solid #686868;margin:0;min-width:990px;padding:0;text-align:center}#header{margin:0;text-align:center}#header h1{float:left;margin:0}#header h1 img{height:40px;margin:10px;margin-left:20px;margin-right:30px}#nav-main{font-family:"Helvetica",sans-serif;font-size:13px;font-weight:bold;text-align:left;text-transform:uppercase;background:#262626}#nav-main div.menubar{margin:0;padding:0}#nav-main div.nav-main-features{list-style:none outside none;background:none repeat scroll 0 0 transparent;display:table-cell;margin:0 0 0 -1px;padding:10px 7px 10px 10px;position:relative}#nav-main div.nav-main-features a{color:#dadada;display:block;float:left;height:18px;padding:15px 20px 7px 7px;position:relative;text-decoration:none;z-index:100}#nav-main div.nav-main-features a:hover{color:#349968}div#main-content{margin-top:50px}table.main-table{width:900px}div.name{padding:10px;padding-top:40px;padding-right:40px;display:block;font:italic 32px/35px;color:#444}div.name a{color:#444;text-decoration:underline}div.subname{font-family:Rosario,sans-serif;font-style:normal;font-size:56px;line-height:50px;text-transform:uppercase;letter-spacing:-3px}div.name p{font:italic 18px;padding-top:12px;letter-spacing:0;font-size:16px;margin:5px 5px 15px}#footer{background:url("../img/background.png") repeat-x scroll 0 0 #339a6b;clear:both;color:#fafafa;display:block;min-width:978px;padding:150px 10px 100px}#footer label{color:#fff;font-family:MetaBlack,"Trebuchet MS",sans-serif;font-size:14px;font-weight:bold;text-transform:uppercase}#footer table.footer-table{width:800px}#footer a{color:#d3ebe3}#footer td.subscribe,#footer td.social{width:25%;line-height:22px}#footer td.tweets{width:40%;padding-right:60px}#footer td.tweets li,#footer td.tweets ul{margin:0;padding:0;list-style:none outside none}#footer input[type="submit"]{background:#0b683c;padding:5px;color:#fafafa;border:0;border-radius:5px}div.errorMessage{background:none repeat scroll 0 0 #b11a04;border:medium none;border-radius:5px 5px 5px 5px;box-shadow:0 3px 0 rgba(0,0,0,0.1),0 1px 10px rgba(0,0,0,0.2);color:#fff;font-family:"Open Sans",sans-serif;padding:10px;margin:10px;text-align:left}div.successMessage{background:none repeat scroll 0 0 #80ba36;border:medium none;border-radius:5px 5px 5px 5px;box-shadow:0 3px 0 rgba(0,0,0,0.1),0 1px 10px rgba(0,0,0,0.2);color:#fff;font-family:"Open Sans",sans-serif;padding:10px;margin:10px;text-align:left}div.download{font-family:"Open Sans",sans-serif;font-style:normal;font-size:20px;letter-spacing:0;text-align:center;padding:10px;display:block;margin:0 0 10px 20px;-moz-box-shadow:0 3px rgba(0,0,0,0.1),inset 0 -4px rgba(0,0,0,0.1);-webkit-box-shadow:0 3px rgba(0,0,0,0.1),inset 0 -4px rgba(0,0,0,0.1);box-shadow:0 3px rgba(0,0,0,0.1),inset 0 -4px rgba(0,0,0,0.1);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;color:white;overflow:visible;background:#58a100;background:-moz-linear-gradient(top,#84c63c 0,#489615 100%);background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#84c63c),color-stop(100%,#489615));background:linear-gradient(top,#84c63c 0,#489615 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#84C63C',endColorstr='#489615',GradientType=0);-moz-transition:box-shadow .2s ease-in-out;-webit-transition:box-shadow .2s ease-in-out;transition:box-shadow .2s ease-in-out;width:150px;zoom:1}div.documentation{background:-moz-linear-gradient(center top,#2d9a6d 0,#227653 100%) repeat scroll 0 0 transparent;background:-webkit-gradient(linear,left top,left bottom,color-stop(0%,#2d9a6d),color-stop(100%,#227653));background:linear-gradient(top,#2d9a6d 0,#227653 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2D9A6D',endColorstr='#227653',GradientType=0);-moz-transition:box-shadow .2s ease-in-out;-webit-transition:box-shadow .2s ease-in-out;transition:box-shadow .2s ease-in-out;border-radius:6px 6px 6px 6px;-moz-box-shadow:0 3px rgba(0,0,0,0.1),inset 0 -4px rgba(0,0,0,0.1);-webkit-box-shadow:0 3px rgba(0,0,0,0.1),inset 0 -4px rgba(0,0,0,0.1);box-shadow:0 3px rgba(0,0,0,0.1),0 -4px rgba(0,0,0,0.1) inset;color:white;font-family:"Open Sans",sans-serif;font-size:20px;font-style:normal;letter-spacing:0;margin:0 0 10px 0;overflow:visible;padding:10px;text-align:center;width:220px}div.name a.no-decoration{text-decoration:none}div.sub-content{border-radius:10px 10px 10px 10px;padding:20px;margin-top:0;width:70%}div.sub{padding:20px;display:table-cell;width:25%;font-size:22px;line-height:24px}div.sub a{color:#333}div.sub img{width:96px}div.sub span{font-size:16px}div.page{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;text-align:center;margin-top:40px}div.subheader{border-bottom:1px solid #666;clear:both;height:34px;margin-bottom:15px}#tabs{float:right;font-weight:bold}#tabs a{background:inherit;border:1px solid #fff;color:#777;display:block;float:left;font-size:90%;height:24px;line-height:22px;margin:8px 8px 0 0;padding:0 11px;text-decoration:none}#tabs a.youarehere{-moz-border-bottom-colors:none;-moz-border-image:none;-moz-border-left-colors:none;-moz-border-right-colors:none;-moz-border-top-colors:none;background:none repeat scroll 0 0 #fff;border-color:#777 #777 #fff;border-style:solid;border-width:1px;color:black;font-size:120%;height:30px;line-height:28px;margin-top:3px;padding:0 11px}h2{color:#000;display:block;font:italic 36px Georgia,"Times New Roman",Times,serif;letter-spacing:-3px;text-rendering:optimizelegibility}.titleContent{letter-spacing:1px;font-size:22px;font-weight:normal}.tableFormat1{font:45px;font-size:15px}.cellDown td{border-bottom:2px solid #DDD;margin-right:10px}.tableFormat2 td{font-size:15px;line-height:23px;text-align:left}.tableFormat2 h4{margin:0;margin-top:15px}.tableFormat2 pre{font-style:normal;line-height:16px}a{color:#08c;text-decoration:none}div.doc-box{background-color:#f5fafa;border-radius:10px 10px 10px 10px;padding:32px;font-family:"Open Sans",sans-serif;line-height:23px;margin-bottom:15px}div.doc-box h2{margin:0;margin-bottom:15px}h3{margin:0;margin-top:15px;margin-bottom:10px}div.doc-box td{color:#333;text-align:left;font-size:16px}div.doc-box img{width:128px;padding-right:20px}table.resume td{border-left:1px solid #dadada;border-bottom:1px solid #dadada}table.resume{border-right:1px solid #dadada;border-top:1px solid #dadada}iframe.present_iframe{border:0;padding:0;margin:0;background:transparent}#github-con{position:absolute;top:0;right:0;width:220px;height:180px;overflow:hidden;padding-top:40px}#github{background-color:#6fb52e;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);transform:rotate(45deg);-webkit-box-shadow:0 0 0 1px #1d212e inset,0 0 2px 1px #fff inset,0 0 1em #333;-moz-box-shadow:0 0 0 1px #1d212e inset,0 0 2px 1px #fff inset,0 0 1em #333;box-shadow:0 0 0 1px #1d212e inset,0 0 2px 1px #fff inset,0 0 1em #333;color:rgba(255,255,255,0.90);padding:.6em 3.5em;font:bold 12px sans-serif;text-align:center;text-decoration:none;text-shadow:1px -1px 8px rgba(0,0,0,0.60);-webkit-user-select:none;-moz-user-select:none;user-select:none}#github a{color:#fff}div.about-bg{background:url("../img/watermark.png") no-repeat scroll 500px 50px #fff;width:99%}div.about{color:#222;width:650px;font-size:16px;text-align:left;margin-left:100px;margin-top:70px;background:rgba(255,255,255,0.7);border-radius:15px;padding-top:10px;line-height:22px}div.about li{color:#222;font-size:16px;text-align:left;line-height:25px;margin:5px} diff --git a/zh/_theme/phalcon/layout.html b/zh/_theme/phalcon/layout.html new file mode 100755 index 000000000000..4d37926fa7ec --- /dev/null +++ b/zh/_theme/phalcon/layout.html @@ -0,0 +1,252 @@ +{%- block doctype -%} + +{%- endblock %} +{%- set reldelim1 = reldelim1 is not defined and ' »' or reldelim1 %} +{%- set reldelim2 = reldelim2 is not defined and ' |' or reldelim2 %} +{%- set url_root = pathto('', 1) %} +{%- if url_root == '#' %}{% set url_root = '' %}{% endif %} + +{%- macro relbar() %} + +{%- endmacro %} + +{%- macro downrelbar() %} + +{%- endmacro %} + +{%- macro sidebar() %} + {%- if not embedded %}{% if not theme_nosidebar|tobool %} +
+ {%- endif %}{% endif %} +{%- endmacro %} + + + + {% if sourcename == "error.txt" %} + + {% endif %} + + {{ metatags }} + {%- if not embedded and docstitle %} + {%- set titlesuffix = " — "|safe + docstitle|e %} + {%- else %} + {%- set titlesuffix = "" %} + {%- endif %} + {{ title|striptags }}{{ titlesuffix }} + + + + + + + + + {%- if not embedded %} + + + + + + {%- if use_opensearch %} + + {%- endif %} + + {%- endif %} +{%- block linktags %} + {%- if hasdoc('about') %} + + {%- endif %} + {%- if hasdoc('genindex') %} + + {%- endif %} + {%- if hasdoc('search') %} + + {%- endif %} + {%- if hasdoc('copyright') %} + + {%- endif %} + + {%- if parents %} + + {%- endif %} + {%- if next %} + + {%- endif %} + {%- if prev %} + + {%- endif %} +{%- endblock %} +{%- block extrahead %} {% endblock %} + + +
+ + + + {%- block header %}{% endblock %} + + {%- block relbar1 %}{{ relbar() }}{% endblock %} + + {%- block sidebar1 %} {# possible location for sidebar #} {% endblock %} + +
+ {%- block sidebarlogo %} + {%- if logo %} + + {%- endif %} + {%- endblock %} + {%- block sidebarsearch %} + {%- if pagename != "search" %} + {% if versions %} +

Project Versions

+ + + {% endif %} + + {%- endif %} + {%- endblock %} + {%- block sidebartoc %} + {%- if display_toc %} +

{{ _('Table Of Contents') }}

+ {{ toc }} + {%- endif %} + {%- endblock %} + {%- block sidebarrel %} + {%- if prev %} +

{{ _('Previous topic') }}

+

{{ prev.title }}

+ {%- endif %} + {%- if next %} +

{{ _('Next topic') }}

+

{{ next.title }}

+ {%- endif %} + {%- endblock %} + {%- block sidebarsourcelink %} + {%- if show_source and has_source and sourcename %} +

{{ _('This Page') }}

+ + {%- endif %} + {%- endblock %} + {%- if customsidebar %} + {% include customsidebar %} + {%- endif %} +
+ + {%- block sidebar2 %}{{ sidebar() }}{% endblock %} + + +
+
+ {%- block document %} +
+ {%- if not embedded %}{% if not theme_nosidebar|tobool %} +
+ {%- endif %}{% endif %} +
+ {% block body %} {% endblock %} +
+ {%- if not embedded %}{% if not theme_nosidebar|tobool %} +
+ {%- endif %}{% endif %} +
+ {%- endblock %} +
+
+ + {%- block relbar2 %}{{ downrelbar() }}{% endblock %} + + {%- block footer %} + + {%- endblock %} + + + + + diff --git a/zh/_theme/phalcon/theme.conf b/zh/_theme/phalcon/theme.conf new file mode 100755 index 000000000000..c0c26e6e58c1 --- /dev/null +++ b/zh/_theme/phalcon/theme.conf @@ -0,0 +1,9 @@ +[theme] +inherit = basic +stylesheet = default.css +pygments_style = sphinx + +[options] +nosidebar = false +body_leftmargin = 0 + diff --git a/zh/api/Phalcon_Acl.rst b/zh/api/Phalcon_Acl.rst new file mode 100755 index 000000000000..0e3ff25f0aa4 --- /dev/null +++ b/zh/api/Phalcon_Acl.rst @@ -0,0 +1,65 @@ +Class **Phalcon\\Acl** +====================== + +This component allows to manage ACL lists. An access control list (ACL) is a list of permissions attached to an object. An ACL specifies which users or system processes are granted access to objects, as well as what operations are allowed on given objects. + +.. code-block:: php + + setDefaultAction(Phalcon\Acl::DENY); + + //Create some roles + $roleAdmins = new Phalcon\Acl\Role('Administrators', 'Super-User role'); + $roleGuests = new Phalcon\Acl\Role('Guests'); + + //Add "Guests" role to acl + $acl->addRole($roleGuests); + + //Add "Designers" role to acl + $acl->addRole('Designers')); + + //Define the "Customers" resource + $customersResource = new Phalcon\Acl\Resource('Customers', 'Customers management'); + + //Add "customers" resource with a couple of operations + $acl->addResource($customersResource, 'search'); + $acl->addResource($customersResource, array('create', 'update')); + + //Set access level for roles into resources + $acl->allow('Guests', 'Customers', 'search'); + $acl->allow('Guests', 'Customers', 'create'); + $acl->deny('Guests', 'Customers', 'update'); + + //Check whether role has access to the operations + $acl->isAllowed('Guests', 'Customers', 'edit') //Returns 0 + $acl->isAllowed('Guests', 'Customers', 'search'); //Returns 1 + $acl->isAllowed('Guests', 'Customers', 'create'); //Returns 1 + + + +Constants +--------- + +*integer* **ALLOW** + +*integer* **DENY** + +Methods +--------- + +public **setEventsManager** (*unknown* $eventsManager) + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + diff --git a/zh/api/Phalcon_Acl_Adapter_Memory.rst b/zh/api/Phalcon_Acl_Adapter_Memory.rst new file mode 100755 index 000000000000..159499d48bc6 --- /dev/null +++ b/zh/api/Phalcon_Acl_Adapter_Memory.rst @@ -0,0 +1,255 @@ +Class **Phalcon\\Acl\\Adapter\\Memory** +======================================= + +*extends* :doc:`Phalcon\\Acl ` + +Manages ACL lists in memory + +.. code-block:: php + + setDefaultAction(Phalcon\Acl::DENY); + + //Register roles + $roles = array( + 'users' => new Phalcon\Acl\Role('Users'), + 'guests' => new Phalcon\Acl\Role('Guests') + ); + foreach($roles as $role){ + $acl->addRole($role); + } + + //Private area resources + $privateResources = array( + 'companies' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'), + 'products' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'), + 'invoices' => array('index', 'profile') + ); + foreach($privateResources as $resource => $actions){ + $acl->addResource(new Phalcon\Acl\Resource($resource), $actions); + } + + //Private area resources + $publicResources = array( + 'index' => array('index'), + 'about' => array('index'), + 'session' => array('index', 'register', 'start', 'end'), + 'contact' => array('index', 'send') + ); + foreach($publicResources as $resource => $actions){ + $acl->addResource(new Phalcon\Acl\Resource($resource), $actions); + } + + //Grant access to public areas to both users and guests + foreach($roles as $role){ + foreach($publicResources as $resource => $actions){ + $acl->allow($role->getName(), $resource, '*'); + } + } + + //Grant acess to private area to role Users + foreach($privateResources as $resource => $actions){ + foreach($actions as $action){ + $acl->allow('Users', $resource, $action); + } + } + + + +Constants +--------- + +*integer* **ALLOW** + +*integer* **DENY** + +Methods +--------- + +public **__construct** () + +... + + +public **setDefaultAction** (*int* $defaultAccess) + +Sets the default access level (Phalcon\\Acl::ALLOW or Phalcon\\Acl::DENY) + + + +public **getDefaultAction** () + +Returns the default ACL access level + + + +public *boolean* **addRole** (*string* $roleObject, *array* $accessInherits) + +Adds a role to the ACL list. Second parameter lets to inherit access data from other existing role Example: + +.. code-block:: php + + addRole(new Phalcon\Acl\Role('administrator'), 'consultant'); + $acl->addRole('administrator', 'consultant'); + + + + +public **addInherit** (*string* $roleName, *string* $roleToInherit) + +Do a role inherit from another existing role + + + +public *boolean* **isRole** (*string* $roleName) + +Check whether role exist in the roles list + + + +public *boolean* **isResource** (*string* $resourceName) + +Check whether resource exist in the resources list + + + +public *boolean* **addResource** (:doc:`Phalcon\\Acl\\Resource ` $resource, *unknown* $accessList) + +Adds a resource to the ACL list Access names can be a particular action, by example search, update, delete, etc or a list of them Example: + +.. code-block:: php + + addResource(new Phalcon\Acl\Resource('customers'), 'search'); + $acl->addResource('customers', 'search'); + + //Add a resource with an access list + $acl->addResource(new Phalcon\Acl\Resource('customers'), array('create', 'search')); + $acl->addResource('customers', array('create', 'search')); + + + + +public **addResourceAccess** (*string* $resourceName, *mixed* $accessList) + +Adds access to resources + + + +public **dropResourceAccess** (*string* $resourceName, *mixed* $accessList) + +Removes an access from a resource + + + +protected **_allowOrDeny** () + +... + + +public **allow** (*string* $roleName, *string* $resourceName, *mixed* $access) + +Allow access to a role on a resource You can use '*' as wildcard Example: + +.. code-block:: php + + allow('guests', 'customers', 'search'); + + //Allow access to guests to search or create on customers + $acl->allow('guests', 'customers', array('search', 'create')); + + //Allow access to any role to browse on products + $acl->allow('*', 'products', 'browse'); + + //Allow access to any role to browse on any resource + $acl->allow('*', '*', 'browse'); + + + + +public *boolean* **deny** (*string* $roleName, *string* $resourceName, *mixed* $access) + +Deny access to a role on a resource You can use '*' as wildcard Example: + +.. code-block:: php + + deny('guests', 'customers', 'search'); + + //Deny access to guests to search or create on customers + $acl->deny('guests', 'customers', array('search', 'create')); + + //Deny access to any role to browse on products + $acl->deny('*', 'products', 'browse'); + + //Deny access to any role to browse on any resource + $acl->deny('*', '*', 'browse'); + + + + +public *boolean* **isAllowed** (*string* $role, *string* $resource, *unknown* $access) + +Check whether a role is allowed to access an action from a resource + +.. code-block:: php + + isAllowed('andres', 'Products', 'create'); + + //Do guests have access to any resource to edit? + $acl->isAllowed('guests', '*', 'edit'); + + + + +public *string* **getActiveRole** () + +Returns the role which the list is checking if it's allowed to certain resource/access + + + +public *string* **getActiveResource** () + +Returns the resource which the list is checking if some role can access it + + + +public *string* **getActiveAccess** () + +Returns the access which the list is checking if some role can access it + + + +protected **_rebuildAccessList** () + +Rebuild the list of access from the inherit lists + + + +public **setEventsManager** (*unknown* $eventsManager) inherited from Phalcon\\Acl + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Acl + +Returns the internal event manager + + + diff --git a/zh/api/Phalcon_Acl_Exception.rst b/zh/api/Phalcon_Acl_Exception.rst new file mode 100755 index 000000000000..1bd424d0277b --- /dev/null +++ b/zh/api/Phalcon_Acl_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Acl\\Exception** +================================= + +*extends* :doc:`Phalcon\\Exception ` + +Class for exceptions thrown by Phalcon\\Acl + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Acl_Resource.rst b/zh/api/Phalcon_Acl_Resource.rst new file mode 100755 index 000000000000..ff3a5a3e4759 --- /dev/null +++ b/zh/api/Phalcon_Acl_Resource.rst @@ -0,0 +1,27 @@ +Class **Phalcon\\Acl\\Resource** +================================ + +This class defines resource entity and its description + + +Methods +--------- + +public **__construct** (*string* $name, *string* $description) + +Phalcon\\Acl\\Resource description + + + +public *string* **getName** () + +Returns the resource name + + + +public *string* **getDescription** () + +Returns resource description + + + diff --git a/zh/api/Phalcon_Acl_Role.rst b/zh/api/Phalcon_Acl_Role.rst new file mode 100755 index 000000000000..5e2294963bf1 --- /dev/null +++ b/zh/api/Phalcon_Acl_Role.rst @@ -0,0 +1,27 @@ +Class **Phalcon\\Acl\\Role** +============================ + +This class defines role entity and its description + + +Methods +--------- + +public **__construct** (*string* $name, *string* $description) + +Phalcon\\Acl\\Role description + + + +public *string* **getName** () + +Returns the role name + + + +public *string* **getDescription** () + +Returns role description + + + diff --git a/zh/api/Phalcon_CLI_Console.rst b/zh/api/Phalcon_CLI_Console.rst new file mode 100644 index 000000000000..b4047061465b --- /dev/null +++ b/zh/api/Phalcon_CLI_Console.rst @@ -0,0 +1,73 @@ +Class **Phalcon\\CLI\\Console** +=============================== + +This component allows to create CLI applications using Phalcon + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public **registerModules** (*array* $modules) + +Register an array of modules present in the console + +.. code-block:: php + + registerModules(array( + 'frontend' => array( + 'className' => 'Multiple\Frontend\Module', + 'path' => '../apps/frontend/Module.php' + ), + 'backend' => array( + 'className' => 'Multiple\Backend\Module', + 'path' => '../apps/backend/Module.php' + ) + )); + + + + +public **addModules** (*array* $modules) + +Merge modules with the existing ones + + + +public *array* **getModules** () + +Return the modules registered in the console + + + +public *mixed* **handle** (*array* $arguments) + +Handle the whole command-line tasks + + + diff --git a/zh/api/Phalcon_CLI_Console_Exception.rst b/zh/api/Phalcon_CLI_Console_Exception.rst new file mode 100644 index 000000000000..87eac59b9bd2 --- /dev/null +++ b/zh/api/Phalcon_CLI_Console_Exception.rst @@ -0,0 +1,68 @@ +Class **Phalcon\\CLI\\Console\\Exception** +========================================== + +*extends* :doc:`Phalcon\\Exception ` + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_CLI_Dispatcher.rst b/zh/api/Phalcon_CLI_Dispatcher.rst new file mode 100644 index 000000000000..639fe6782583 --- /dev/null +++ b/zh/api/Phalcon_CLI_Dispatcher.rst @@ -0,0 +1,190 @@ +Class **Phalcon\\CLI\\Dispatcher** +================================== + +*extends* :doc:`Phalcon\\Dispatcher ` + +Dispatching is the process of taking the command-line arguments, extracting the module name, task name, action name, and optional parameters contained in it, and then instantiating a task and calling an action on it. + +.. code-block:: php + + setDI($di); + + $dispatcher->setTaskName('posts'); + $dispatcher->setActionName('index'); + $dispatcher->setParams(array()); + + $handle = $dispatcher->dispatch(); + + + +Constants +--------- + +*integer* **EXCEPTION_NO_DI** + +*integer* **EXCEPTION_CYCLIC_ROUTING** + +*integer* **EXCEPTION_HANDLER_NOT_FOUND** + +*integer* **EXCEPTION_INVALID_PARAMS** + +*integer* **EXCEPTION_ACTION_NOT_FOUND** + +Methods +--------- + +public **setTaskSuffix** (*string* $taskSuffix) + +Sets the default task suffix + + + +public **setDefaultTask** (*string* $taskName) + +Sets the default task name + + + +public **setTaskName** (*string* $taskName) + +Sets the task name to be dispatched + + + +public *string* **getTaskName** () + +Gets last dispatched task name + + + +protected **_throwDispatchException** () + +Throws an internal exception + + + +public :doc:`Phalcon\\CLI\\Task ` **getLastTask** () + +Returns the lastest dispatched controller + + + +public :doc:`Phalcon\\CLI\\Task ` **getActiveTask** () + +Returns the active task in the dispatcher + + + +public **__construct** () inherited from Phalcon\\Dispatcher + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\Dispatcher + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\Dispatcher + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\Dispatcher + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Dispatcher + +Returns the internal event manager + + + +public **setActionSuffix** (*string* $actionSuffix) inherited from Phalcon\\Dispatcher + +Sets the default action suffix + + + +public **setDefaultNamespace** (*string* $namespace) inherited from Phalcon\\Dispatcher + +Sets the default namespace + + + +public **setDefaultAction** (*string* $actionName) inherited from Phalcon\\Dispatcher + +Sets the default action name + + + +public **setActionName** (*string* $actionName) inherited from Phalcon\\Dispatcher + +Sets the action name to be dispatched + + + +public *string* **getActionName** () inherited from Phalcon\\Dispatcher + +Gets last dispatched action name + + + +public **setParams** (*array* $params) inherited from Phalcon\\Dispatcher + +Sets action params to be dispatched + + + +public *array* **getParams** () inherited from Phalcon\\Dispatcher + +Gets action params + + + +public **setParam** (*mixed* $param, *mixed* $value) inherited from Phalcon\\Dispatcher + +Set a param by its name or numeric index + + + +public *mixed* **getParam** (*mixed* $param, *string|array* $filters) inherited from Phalcon\\Dispatcher + +Gets a param by its name or numeric index + + + +public *boolean* **isFinished** () inherited from Phalcon\\Dispatcher + +Checks if the dispatch loop is finished or have more pendent controllers/tasks to disptach + + + +public *mixed* **getReturnedValue** () inherited from Phalcon\\Dispatcher + +Returns value returned by the lastest dispatched action + + + +public *object* **dispatch** () inherited from Phalcon\\Dispatcher + +Dispatches a handle action taking into account the routing parameters + + + +public **forward** (*array* $forward) inherited from Phalcon\\Dispatcher + +Forwards the execution flow to another controller/action + + + diff --git a/zh/api/Phalcon_CLI_Dispatcher_Exception.rst b/zh/api/Phalcon_CLI_Dispatcher_Exception.rst new file mode 100644 index 000000000000..301c67772a56 --- /dev/null +++ b/zh/api/Phalcon_CLI_Dispatcher_Exception.rst @@ -0,0 +1,68 @@ +Class **Phalcon\\CLI\\Dispatcher\\Exception** +============================================= + +*extends* :doc:`Phalcon\\Exception ` + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_CLI_Router.rst b/zh/api/Phalcon_CLI_Router.rst new file mode 100644 index 000000000000..34564469fe09 --- /dev/null +++ b/zh/api/Phalcon_CLI_Router.rst @@ -0,0 +1,83 @@ +Class **Phalcon\\CLI\\Router** +============================== + +Phalcon\\CLI\\Router is the standard framework router. Routing is the process of taking a command-line arguments and decomposing it into parameters to determine which module, task, and action of that task should receive the request + +.. code-block:: php + + handle(array()); + echo $router->getTaskName(); + + + +Methods +--------- + +public **__construct** () + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +public **setDefaultModule** (*string* $moduleName) + +Sets the name of the default module + + + +public **setDefaultTask** (*unknown* $taskName) + +Sets the default controller name + + + +public **setDefaultAction** (*string* $actionName) + +Sets the default action name + + + +public **handle** (*array* $arguments) + +Handles routing information received from command-line arguments + + + +public *string* **getModuleName** () + +Returns proccesed module name + + + +public *string* **getTaskName** () + +Returns proccesed task name + + + +public *string* **getActionName** () + +Returns proccesed action name + + + +public *array* **getParams** () + +Returns proccesed extra params + + + diff --git a/zh/api/Phalcon_CLI_Router_Exception.rst b/zh/api/Phalcon_CLI_Router_Exception.rst new file mode 100644 index 000000000000..29aa74ca1fd7 --- /dev/null +++ b/zh/api/Phalcon_CLI_Router_Exception.rst @@ -0,0 +1,68 @@ +Class **Phalcon\\CLI\\Router\\Exception** +========================================= + +*extends* :doc:`Phalcon\\Exception ` + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_CLI_Task.rst b/zh/api/Phalcon_CLI_Task.rst new file mode 100644 index 000000000000..9250d4cd07f3 --- /dev/null +++ b/zh/api/Phalcon_CLI_Task.rst @@ -0,0 +1,43 @@ +Class **Phalcon\\CLI\\Task** +============================ + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +Methods +--------- + +final public **__construct** () + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Cache_Backend.rst b/zh/api/Phalcon_Cache_Backend.rst new file mode 100755 index 000000000000..d0af231db11c --- /dev/null +++ b/zh/api/Phalcon_Cache_Backend.rst @@ -0,0 +1,50 @@ +Class **Phalcon\\Cache\\Backend** +================================= + +This class implements common functionality for backend adapters. All the backend cache adapter must extend this class + + +Methods +--------- + +public **__construct** (*mixed* $frontendObject, *array* $backendOptions) + +Phalcon\\Cache\\Backend constructor + + + +public *mixed* **start** (*int|string* $keyName) + +Starts a cache. The $keyname allow to identify the created fragment + + + +public *mixed* **getFrontend** () + +Returns front-end instance adapter related to the back-end + + + +public *boolean* **isFresh** () + +Checks whether the last cache is fresh or cached + + + +public *boolean* **isStarted** () + +Checks whether the cache has started buffering or not + + + +public *string* **getLastKey** () + +Gets the last key stored by the cache + + + +abstract public **get** () + +... + + diff --git a/zh/api/Phalcon_Cache_Backend_Apc.rst b/zh/api/Phalcon_Cache_Backend_Apc.rst new file mode 100755 index 000000000000..4fa2efeb265c --- /dev/null +++ b/zh/api/Phalcon_Cache_Backend_Apc.rst @@ -0,0 +1,100 @@ +Class **Phalcon\\Cache\\Backend\\Apc** +====================================== + +*extends* :doc:`Phalcon\\Cache\\Backend ` + +Allows to cache output fragments, PHP data and raw data using a memcache backend + +.. code-block:: php + + 172800 + ); + + //Cache data for 2 days + $frontCache = new Phalcon\Cache\Frontend\Data(array( + 'lifetime' => 172800 + )); + + $cache = new Phalcon\Cache\Backend\Apc($frontCache); + + //Cache arbitrary data + $cache->store('my-data', array(1, 2, 3, 4, 5)); + + //Get data + $data = $cache->get('my-data'); + + + +Methods +--------- + +public *mixed* **get** (*string* $keyName, *long* $lifetime) + +Returns a cached content + + + +public **save** (*string* $keyName, *string* $content, *long* $lifetime, *boolean* $stopBuffer) + +Stores cached content into the file backend + + + +public *boolean* **delete** (*string* $keyName) + +Deletes a value from the cache by its key + + + +public *array* **queryKeys** (*string* $prefix) + +Query the existing cached keys + + + +public *boolean* **exists** (*string* $keyName) + +Checks if cache exists. + + + +public **__construct** (*mixed* $frontendObject, *array* $backendOptions) inherited from Phalcon\\Cache\\Backend + +Phalcon\\Cache\\Backend constructor + + + +public *mixed* **start** (*int|string* $keyName) inherited from Phalcon\\Cache\\Backend + +Starts a cache. The $keyname allow to identify the created fragment + + + +public *mixed* **getFrontend** () inherited from Phalcon\\Cache\\Backend + +Returns front-end instance adapter related to the back-end + + + +public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend + +Checks whether the last cache is fresh or cached + + + +public *boolean* **isStarted** () inherited from Phalcon\\Cache\\Backend + +Checks whether the cache has started buffering or not + + + +public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend + +Gets the last key stored by the cache + + + diff --git a/zh/api/Phalcon_Cache_Backend_File.rst b/zh/api/Phalcon_Cache_Backend_File.rst new file mode 100755 index 000000000000..aec3d26cc41b --- /dev/null +++ b/zh/api/Phalcon_Cache_Backend_File.rst @@ -0,0 +1,102 @@ +Class **Phalcon\\Cache\\Backend\\File** +======================================= + +*extends* :doc:`Phalcon\\Cache\\Backend ` + +Allows to cache output fragments using a file backend + +.. code-block:: php + + 172800 + ); + + //Set the cache directory + $backendOptions = array( + 'cacheDir' => '../app/cache/' + ); + + $cache = Phalcon_Cache::factory('Output', 'File', $frontendOptions, $backendOptions); + + $content = $cache->start('my-cache'); + if($content===null){ + echo '

', time(), '

'; + $cache->save(); + } else { + echo $content; + } + + + +Methods +--------- + +public **__construct** (*mixed* $frontendObject, *array* $backendOptions) + +Phalcon\\Backend\\Adapter\\File constructor + + + +public *mixed* **get** (*int|string* $keyName, *long* $lifetime) + +Returns a cached content + + + +public **save** (*int|string* $keyName, *string* $content, *long* $lifetime, *boolean* $stopBuffer) + +Stores cached content into the file backend + + + +public *boolean* **delete** (*int|string* $keyName) + +Deletes a value from the cache by its key + + + +public *array* **queryKeys** (*string* $prefix) + +Query the existing cached keys + + + +public *boolean* **exists** (*string* $keyName) + +Checks if cache exists. + + + +public *mixed* **start** (*int|string* $keyName) inherited from Phalcon\\Cache\\Backend + +Starts a cache. The $keyname allow to identify the created fragment + + + +public *mixed* **getFrontend** () inherited from Phalcon\\Cache\\Backend + +Returns front-end instance adapter related to the back-end + + + +public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend + +Checks whether the last cache is fresh or cached + + + +public *boolean* **isStarted** () inherited from Phalcon\\Cache\\Backend + +Checks whether the cache has started buffering or not + + + +public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend + +Gets the last key stored by the cache + + + diff --git a/zh/api/Phalcon_Cache_Backend_Memcache.rst b/zh/api/Phalcon_Cache_Backend_Memcache.rst new file mode 100755 index 000000000000..9d2eac277fb8 --- /dev/null +++ b/zh/api/Phalcon_Cache_Backend_Memcache.rst @@ -0,0 +1,112 @@ +Class **Phalcon\\Cache\\Backend\\Memcache** +=========================================== + +*extends* :doc:`Phalcon\\Cache\\Backend ` + +Allows to cache output fragments, PHP data or raw data to a memcache backend This adapter uses the special memcached key "_PHCM" to store all the keys internally used by the adapter + +.. code-block:: php + + 172800 + )); + + //Create the Cache setting memcached connection options + $cache = new Phalcon\Cache\Backend\File($frontCache, array( + 'host' => 'localhost', + 'port' => 11211, + 'persistent' => false + )); + + //Cache arbitrary data + $cache->store('my-data', array(1, 2, 3, 4, 5)); + + //Get data + $data = $cache->get('my-data'); + + + +Methods +--------- + +public **__construct** (*mixed* $frontendObject, *array* $backendOptions) + +Phalcon\\Backend\\Adapter\\Memcache constructor + + + +protected **_connect** () + +Create internal connection to memcached + + + +public *mixed* **get** (*int|string* $keyName, *long* $lifetime) + +Returns a cached content + + + +public **save** (*int|string* $keyName, *string* $content, *long* $lifetime, *boolean* $stopBuffer) + +Stores cached content into the Memcached backend + + + +public *boolean* **delete** (*int|string* $keyName) + +Deletes a value from the cache by its key + + + +public *array* **queryKeys** (*string* $prefix) + +Query the existing cached keys + + + +public *boolean* **exists** (*string* $keyName) + +Checks if cache exists. + + + +public **__destruct** () + +Destructs the backend closing the memcached connection + + + +public *mixed* **start** (*int|string* $keyName) inherited from Phalcon\\Cache\\Backend + +Starts a cache. The $keyname allow to identify the created fragment + + + +public *mixed* **getFrontend** () inherited from Phalcon\\Cache\\Backend + +Returns front-end instance adapter related to the back-end + + + +public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend + +Checks whether the last cache is fresh or cached + + + +public *boolean* **isStarted** () inherited from Phalcon\\Cache\\Backend + +Checks whether the cache has started buffering or not + + + +public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend + +Gets the last key stored by the cache + + + diff --git a/zh/api/Phalcon_Cache_Backend_Mongo.rst b/zh/api/Phalcon_Cache_Backend_Mongo.rst new file mode 100644 index 000000000000..eb393460b9fc --- /dev/null +++ b/zh/api/Phalcon_Cache_Backend_Mongo.rst @@ -0,0 +1,106 @@ +Class **Phalcon\\Cache\\Backend\\Mongo** +======================================== + +*extends* :doc:`Phalcon\\Cache\\Backend ` + +Allows to cache output fragments, PHP data or raw data to a MongoDb backend + +.. code-block:: php + + 172800 + )); + + //Create a MongoDB cache + $cache = new Phalcon\Cache\Backend\Mongo($frontCache, array( + 'server' => "mongodb://localhost", + 'db' => 'caches', + 'collection' => 'images' + )); + + //Cache arbitrary data + $cache->store('my-data', file_get_contents('some-image.jpg')); + + //Get data + $data = $cache->get('my-data'); + + + +Methods +--------- + +public **__construct** (*mixed* $frontendObject, *array* $backendOptions) + +Phalcon\\Backend\\Adapter\\Mongo constructor + + + +protected *MongoCollection* **_getCollection** () + +Returns a MongoDb collection based on the backend parameters + + + +public *mixed* **get** (*int|string* $keyName, *long* $lifetime) + +Returns a cached content + + + +public **save** (*int|string* $keyName, *string* $content, *long* $lifetime, *boolean* $stopBuffer) + +Stores cached content into the Mongo backend + + + +public *boolean* **delete** (*int|string* $keyName) + +Deletes a value from the cache by its key + + + +public *array* **queryKeys** (*string* $prefix) + +Query the existing cached keys + + + +public *boolean* **exists** (*string* $keyName) + +Checks if cache exists. + + + +public *mixed* **start** (*int|string* $keyName) inherited from Phalcon\\Cache\\Backend + +Starts a cache. The $keyname allow to identify the created fragment + + + +public *mixed* **getFrontend** () inherited from Phalcon\\Cache\\Backend + +Returns front-end instance adapter related to the back-end + + + +public *boolean* **isFresh** () inherited from Phalcon\\Cache\\Backend + +Checks whether the last cache is fresh or cached + + + +public *boolean* **isStarted** () inherited from Phalcon\\Cache\\Backend + +Checks whether the cache has started buffering or not + + + +public *string* **getLastKey** () inherited from Phalcon\\Cache\\Backend + +Gets the last key stored by the cache + + + diff --git a/zh/api/Phalcon_Cache_Exception.rst b/zh/api/Phalcon_Cache_Exception.rst new file mode 100755 index 000000000000..fd17119ef7d4 --- /dev/null +++ b/zh/api/Phalcon_Cache_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Cache\\Exception** +=================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon_Cache will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Cache_Frontend_Base64.rst b/zh/api/Phalcon_Cache_Frontend_Base64.rst new file mode 100644 index 000000000000..3471a8444964 --- /dev/null +++ b/zh/api/Phalcon_Cache_Frontend_Base64.rst @@ -0,0 +1,78 @@ +Class **Phalcon\\Cache\\Frontend\\Base64** +========================================== + +Allows to cache data converting/deconverting them to base64. This adapters uses the base64_encode/base64_decode PHP's functions + +.. code-block:: php + + 172800 + )); + + //Create a MongoDB cache + $cache = new Phalcon\Cache\Backend\Mongo($frontCache, array( + 'server' => "mongodb://localhost", + 'db' => 'caches', + 'collection' => 'images' + )); + + // Try to get cached image + $cacheKey = 'some-image.jpg.cache'; + $image = $cache->get($cacheKey); + if ($image === null) { + + // Store the image in the cache + $cache->save($cacheKey, file_put_contents('tmp-dir/some-image.jpg')); + } + + header('Content-Type: image/jpeg'); + echo $image; + + + +Methods +--------- + +public **__construct** (*unknown* $frontendOptions) + +... + + +public **getLifetime** () + +... + + +public **isBuffering** () + +... + + +public **start** () + +... + + +public **getContent** () + +... + + +public **stop** () + +... + + +public **beforeStore** (*unknown* $data) + +... + + +public **afterRetrieve** (*unknown* $data) + +... + + diff --git a/zh/api/Phalcon_Cache_Frontend_Data.rst b/zh/api/Phalcon_Cache_Frontend_Data.rst new file mode 100755 index 000000000000..fda959348a29 --- /dev/null +++ b/zh/api/Phalcon_Cache_Frontend_Data.rst @@ -0,0 +1,92 @@ +Class **Phalcon\\Cache\\Frontend\\Data** +======================================== + +Allows to cache native PHP data in a serialized form + +.. code-block:: php + + 172800 + )); + + // Create the component that will cache "Data" to a "File" backend + // Set the cache file directory - important to keep the "/" at the end of + // of the value for the folder + $cache = new Phalcon\Cache\Backend\File($frontCache, array( + "cacheDir" => "../app/cache/" + )); + + // Try to get cached records + $cacheKey = 'robots_order_id.cache'; + $robots = $cache->get($cacheKey); + if ($robots === null) { + + // $robots is null due to cache expiration or data does not exist + // Make the database call and populate the variable + $robots = Robots::find(array("order" => "id")); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + + +Methods +--------- + +public **__construct** (*array* $frontendOptions) + +Phalcon\\Cache\\Frontend\\Data constructor + + + +public *integer* **getLifetime** () + +Returns cache lifetime + + + +public **isBuffering** () + +Check whether if frontend is buffering output + + + +public **start** () + +Starts output frontend. Actually, does nothing + + + +public *string* **getContent** () + +Returns output cached content + + + +public **stop** () + +Stops output frontend + + + +public **beforeStore** (*mixed* $data) + +Serializes data before storing it + + + +public **afterRetrieve** (*mixed* $data) + +Unserializes data after retrieving it + + + diff --git a/zh/api/Phalcon_Cache_Frontend_None.rst b/zh/api/Phalcon_Cache_Frontend_None.rst new file mode 100755 index 000000000000..f1de7fcbb600 --- /dev/null +++ b/zh/api/Phalcon_Cache_Frontend_None.rst @@ -0,0 +1,89 @@ +Class **Phalcon\\Cache\\Frontend\\None** +======================================== + +Discards any kind of frontend data input. This frontend does not have expiration time or any other options + +.. code-block:: php + + "localhost", + "port" => "11211" + )); + + // This Frontend always return the data as it's returned by the backend + $cacheKey = 'robots_order_id.cache'; + $robots = $cache->get($cacheKey); + if ($robots === null) { + + // This cache doesn't perform any expiration checking, so the data is always expired + // Make the database call and populate the variable + $robots = Robots::find(array("order" => "id")); + + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + + +Methods +--------- + +public **__construct** (*unknown* $frontendOptions) + +Phalcon\\Cache\\Frontend\\None constructor + + + +public **getLifetime** () + +Returns cache lifetime, always one second expiring content + + + +public **isBuffering** () + +Check whether if frontend is buffering output, always false + + + +public **start** () + +Starts output frontend + + + +public *string* **getContent** () + +Returns output cached content + + + +public **stop** () + +Stops output frontend + + + +public **beforeStore** (*mixed* $data) + +Prepare data to be stored + + + +public **afterRetrieve** (*mixed* $data) + +Prepares data to be retrieved to user + + + diff --git a/zh/api/Phalcon_Cache_Frontend_Output.rst b/zh/api/Phalcon_Cache_Frontend_Output.rst new file mode 100755 index 000000000000..24a78aee1c37 --- /dev/null +++ b/zh/api/Phalcon_Cache_Frontend_Output.rst @@ -0,0 +1,101 @@ +Class **Phalcon\\Cache\\Frontend\\Output** +========================================== + +Allows to cache output fragments captured with ob_* functions + +.. code-block:: php + + 172800 + )); + + // Create the component that will cache from the "Output" to a "File" backend + // Set the cache file directory - it's important to keep the "/" at the end of + // the value for the folder + $cache = new Phalcon\Cache\Backend\File($frontCache, array( + "cacheDir" => "../app/cache/" + )); + + // Get/Set the cache file to ../app/cache/my-cache.html + $content = $cache->start("my-cache.html"); + + // If $content is null then the content will be generated for the cache + if ($content === null) { + + //Print date and time + echo date("r"); + + //Generate a link to the sign-up action + echo Phalcon\Tag::linkTo( + array( + "user/signup", + "Sign Up", + "class" => "signup-button" + ) + ); + + // Store the output into the cache file + $cache->save(); + + } else { + + // Echo the cached output + echo $content; + } + + + +Methods +--------- + +public **__construct** (*array* $frontendOptions) + +Phalcon\\Cache\\Frontend\\Output constructor + + + +public *integer* **getLifetime** () + +Returns cache lifetime + + + +public **isBuffering** () + +Check whether if frontend is buffering output + + + +public **start** () + +Starts output frontend + + + +public *string* **getContent** () + +Returns output cached content + + + +public **stop** () + +Stops output frontend + + + +public **beforeStore** (*mixed* $data) + +Prepare data to be stored + + + +public **afterRetrieve** (*mixed* $data) + +Prepares data to be retrieved to user + + + diff --git a/zh/api/Phalcon_Config.rst b/zh/api/Phalcon_Config.rst new file mode 100755 index 000000000000..989f25dd0e2e --- /dev/null +++ b/zh/api/Phalcon_Config.rst @@ -0,0 +1,35 @@ +Class **Phalcon\\Config** +========================= + +Phalcon\\Config is designed to simplify the access to, and the use of, configuration data within applications. It provides a nested object property based user interface for accessing this configuration data within application code. + +.. code-block:: php + + array( + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "name" => "test_db" + ), + "phalcon" => array( + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/" + ) + +)); + + +Methods +--------- + +public :doc:`Phalcon\\Config ` **__construct** (*array* $arrayConfig) + +Phalcon\\Config constructor + + + diff --git a/zh/api/Phalcon_Config_Adapter_Ini.rst b/zh/api/Phalcon_Config_Adapter_Ini.rst new file mode 100755 index 000000000000..abc1bbbb89f0 --- /dev/null +++ b/zh/api/Phalcon_Config_Adapter_Ini.rst @@ -0,0 +1,44 @@ +Class **Phalcon\\Config\\Adapter\\Ini** +======================================= + +*extends* :doc:`Phalcon\\Config ` + +Reads ini files and convert it to Phalcon\\Config objects. Given the next configuration file: + +.. code-block:: ini + + phalcon->controllersDir; + echo $config->database->username; + + + +Methods +--------- + +public :doc:`Phalcon\\Config\\Adapter\\Ini ` **__construct** (*string* $filePath) + +Phalcon\\Config\\Adapter\\Ini constructor + + + diff --git a/zh/api/Phalcon_Config_Exception.rst b/zh/api/Phalcon_Config_Exception.rst new file mode 100755 index 000000000000..b6c76c2d7afe --- /dev/null +++ b/zh/api/Phalcon_Config_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Config\\Exception** +==================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Config will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_DI.rst b/zh/api/Phalcon_DI.rst new file mode 100644 index 000000000000..4bc809634530 --- /dev/null +++ b/zh/api/Phalcon_DI.rst @@ -0,0 +1,87 @@ +Class **Phalcon\\DI** +===================== + +Phalcon\\DI is a component that implements Dependency Injection of services and it's itself a container for them. Since Phalcon is highly decoupled, Phalcon\\DI is essential to integrate the different components of the framework. The developer can also use this component to inject dependencies and manage global instances of the different classes used in the application. Basically, this component implements the `Inversion of Control` pattern. Applying this, the objects do not receive their dependencies using setters or constructors, but requesting a service dependency injector. This reduces the overall complexity, since there is only one way to get the required dependencies within a component. Additionally, this pattern increases testability in the code, thus making it less prone to errors. + + +Methods +--------- + +public **__construct** () + +Phalcon\\DI constructor + + + +public :doc:`Phalcon\\DI ` **set** (*string* $alias, *mixed* $config) + +Registers a service in the services container + + + +public :doc:`Phalcon\\DI ` **remove** (*string* $alias) + +Removes a service in the services container + + + +public :doc:`Phalcon\\DI ` **attempt** (*string* $alias, *mixed* $config) + +Attempts to register a service in the services container Only is successful if a services hasn't been registered previosly with the same name + + + +public *mixed* **_factory** (*string* $service, *mixed* $parameters) + +Factories instances based on its config + + + +public *mixed* **get** (*string* $alias, *array* $parameters) + +Resolves the service based on its configuration + + + +public *mixed* **getShared** (*string* $alias, *array* $parameters) + +Returns a shared service based on its configuration + + + +public *boolean* **has** (*unknown* $alias) + +Check whether the DI contains a service by a name + + + +public *boolean* **wasFreshInstance** () + +Check whether the last service obtained via getShared produced a fresh instance or an existing one + + + +public *mixed* **__call** (*string* $method, *array* $arguments) + +Magic method to get or set services using setters/getters + + + +public static **setDefault** (*string* $dependencyInjector) + +Set a default dependency injection container to be obtained into static methods + + + +public static :doc:`Phalcon\\DI ` **getDefault** () + +Return the last DI created + + + +public static **reset** () + +Resets the internal default DI + + + diff --git a/zh/api/Phalcon_DI_Exception.rst b/zh/api/Phalcon_DI_Exception.rst new file mode 100644 index 000000000000..e0fa4f316b7f --- /dev/null +++ b/zh/api/Phalcon_DI_Exception.rst @@ -0,0 +1,68 @@ +Class **Phalcon\\DI\\Exception** +================================ + +*extends* :doc:`Phalcon\\Exception ` + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_DI_FactoryDefault.rst b/zh/api/Phalcon_DI_FactoryDefault.rst new file mode 100644 index 000000000000..80862274b302 --- /dev/null +++ b/zh/api/Phalcon_DI_FactoryDefault.rst @@ -0,0 +1,89 @@ +Class **Phalcon\\DI\\FactoryDefault** +===================================== + +*extends* :doc:`Phalcon\\DI ` + +This is a variant of the standard Phalcon\\DI. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually. + + +Methods +--------- + +public **__construct** () + +Phalcon\\DI\\FactoryDefault constructor + + + +public :doc:`Phalcon\\DI ` **set** (*string* $alias, *mixed* $config) inherited from Phalcon\\DI + +Registers a service in the services container + + + +public :doc:`Phalcon\\DI ` **remove** (*string* $alias) inherited from Phalcon\\DI + +Removes a service in the services container + + + +public :doc:`Phalcon\\DI ` **attempt** (*string* $alias, *mixed* $config) inherited from Phalcon\\DI + +Attempts to register a service in the services container Only is successful if a services hasn't been registered previosly with the same name + + + +public *mixed* **_factory** (*string* $service, *mixed* $parameters) inherited from Phalcon\\DI + +Factories instances based on its config + + + +public *mixed* **get** (*string* $alias, *array* $parameters) inherited from Phalcon\\DI + +Resolves the service based on its configuration + + + +public *mixed* **getShared** (*string* $alias, *array* $parameters) inherited from Phalcon\\DI + +Returns a shared service based on its configuration + + + +public *boolean* **has** (*unknown* $alias) inherited from Phalcon\\DI + +Check whether the DI contains a service by a name + + + +public *boolean* **wasFreshInstance** () inherited from Phalcon\\DI + +Check whether the last service obtained via getShared produced a fresh instance or an existing one + + + +public *mixed* **__call** (*string* $method, *array* $arguments) inherited from Phalcon\\DI + +Magic method to get or set services using setters/getters + + + +public static **setDefault** (*string* $dependencyInjector) inherited from Phalcon\\DI + +Set a default dependency injection container to be obtained into static methods + + + +public static :doc:`Phalcon\\DI ` **getDefault** () inherited from Phalcon\\DI + +Return the last DI created + + + +public static **reset** () inherited from Phalcon\\DI + +Resets the internal default DI + + + diff --git a/zh/api/Phalcon_DI_FactoryDefault_CLI.rst b/zh/api/Phalcon_DI_FactoryDefault_CLI.rst new file mode 100644 index 000000000000..731c87d16256 --- /dev/null +++ b/zh/api/Phalcon_DI_FactoryDefault_CLI.rst @@ -0,0 +1,89 @@ +Class **Phalcon\\DI\\FactoryDefault\\CLI** +========================================== + +*extends* :doc:`Phalcon\\DI\\FactoryDefault ` + +This is a variant of the standard Phalcon\\DI. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually. This class is specially suitable for CLI applications + + +Methods +--------- + +public **__construct** () + +Phalcon\\DI\\FactoryDefault\\CLI constructor + + + +public :doc:`Phalcon\\DI ` **set** (*string* $alias, *mixed* $config) inherited from Phalcon\\DI + +Registers a service in the services container + + + +public :doc:`Phalcon\\DI ` **remove** (*string* $alias) inherited from Phalcon\\DI + +Removes a service in the services container + + + +public :doc:`Phalcon\\DI ` **attempt** (*string* $alias, *mixed* $config) inherited from Phalcon\\DI + +Attempts to register a service in the services container Only is successful if a services hasn't been registered previosly with the same name + + + +public *mixed* **_factory** (*string* $service, *mixed* $parameters) inherited from Phalcon\\DI + +Factories instances based on its config + + + +public *mixed* **get** (*string* $alias, *array* $parameters) inherited from Phalcon\\DI + +Resolves the service based on its configuration + + + +public *mixed* **getShared** (*string* $alias, *array* $parameters) inherited from Phalcon\\DI + +Returns a shared service based on its configuration + + + +public *boolean* **has** (*unknown* $alias) inherited from Phalcon\\DI + +Check whether the DI contains a service by a name + + + +public *boolean* **wasFreshInstance** () inherited from Phalcon\\DI + +Check whether the last service obtained via getShared produced a fresh instance or an existing one + + + +public *mixed* **__call** (*string* $method, *array* $arguments) inherited from Phalcon\\DI + +Magic method to get or set services using setters/getters + + + +public static **setDefault** (*string* $dependencyInjector) inherited from Phalcon\\DI + +Set a default dependency injection container to be obtained into static methods + + + +public static :doc:`Phalcon\\DI ` **getDefault** () inherited from Phalcon\\DI + +Return the last DI created + + + +public static **reset** () inherited from Phalcon\\DI + +Resets the internal default DI + + + diff --git a/zh/api/Phalcon_DI_Injectable.rst b/zh/api/Phalcon_DI_Injectable.rst new file mode 100644 index 000000000000..3ff3fccf3b6d --- /dev/null +++ b/zh/api/Phalcon_DI_Injectable.rst @@ -0,0 +1,39 @@ +Class **Phalcon\\DI\\Injectable** +================================= + +This class allows to access services in the services container by just only accessing a public property with the same name of a registered service + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) + +Magic method __get + + + diff --git a/zh/api/Phalcon_Db.rst b/zh/api/Phalcon_Db.rst new file mode 100755 index 000000000000..50006510903b --- /dev/null +++ b/zh/api/Phalcon_Db.rst @@ -0,0 +1,334 @@ +Class **Phalcon\\Db** +===================== + +Phalcon\\Db and its related classes provide a simple SQL database interface for Phalcon Framework. The Phalcon\\Db is the basic class you use to connect your PHP application to an RDBMS. There is a different adapter class for each brand of RDBMS. This component is intended to lower level database operations. If you want to interact with databases using higher level of abstraction use Phalcon\\Mvc\\Model. Phalcon\\Db is an abstract class. You only can use it with a database adapter like Phalcon\\Db\\Adapter\\Pdo + +.. code-block:: php + + '192.168.0.11', + 'username' => 'sigma', + 'password' => 'secret', + 'dbname' => 'blog', + 'port' => '3306', + )); + + $result = $connection->query("SELECT * FROM robots LIMIT 5"); + $result->setFetchMode(Phalcon\Db::FETCH_NUM); + while($robot = $result->fetchArray()){ + print_r($robot); + } + + } catch(Phalcon\Db\Exception $e){ + echo $e->getMessage(), PHP_EOL; + } + + + +Constants +--------- + +*integer* **FETCH_ASSOC** + +*integer* **FETCH_BOTH** + +*integer* **FETCH_NUM** + +Methods +--------- + +protected **__construct** () + +Phalcon\\Db constructor + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode) + +Returns the first row in a SQL query result + +.. code-block:: php + + fecthOne("SELECT * FROM robots"); + print_r($robot); + + //Getting first robot with associative indexes only + $robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + print_r($robot); + + + + +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode) + +Dumps the complete result of a query into an array + +.. code-block:: php + + fetchAll("SELECT * FROM robots"); + foreach($robots as $robot){ + print_r($robot); + } + + //Getting all robots with associative indexes only + $robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + foreach($robots as $robot){ + print_r($robot); + } + + + + +public *boolean* **insert** (*string* $table, *array* $values, *array* $fields, *array* $dataTypes) + +Inserts data into a table using custom RBDM SQL syntax + +.. code-block:: php + + insert( + "robots", + array("Astro Boy", 1952), + array("name", "year") + ); + + //Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + + + + +public *boolean* **update** (*string* $table, *array* $fields, *array* $values, *string* $whereCondition, *array* $dataTypes) + +Updates data on a table using custom RBDM SQL syntax + +.. code-block:: php + + update( + "robots", + array("name") + array("New Astro Boy"), + "id = 101" + ); + + //Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + + + +public *boolean* **delete** (*string* $table, *string* $whereCondition, *array* $placeholders, *array* $dataTypes) + +Deletes data from a table using custom RBDM SQL syntax + +.. code-block:: php + + delete( + "robots", + "id = 101" + ); + + //Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public *string* **getColumnList** (*array* $columnList) + +Gets a list of columns + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) + +Appends a LIMIT clause to $sqlQuery argument $connection->limit("SELECT * FROM robots", 5); + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) + +Generates SQL checking for the existence of a schema.table $connection->tableExists("blog", "posts") + + + +public *string* **viewExists** (*string* $viewName, *string* $schemaName) + +Generates SQL checking for the existence of a schema.view $connection->viewExists("active_users", "posts") + + + +public *string* **forUpdate** (*string* $sqlQuery) + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *boolean* **createTable** (*string* $tableName, *string* $schemaName, *array* $definition) + +Creates a table using MySQL SQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) + +Drops a table from a schema/database + + + +public *boolean* **addColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) + +Adds a column to a table + + + +public *boolean* **modifyColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) + +Modifies a table column based on a definition + + + +public *boolean* **dropColumn** (*string* $tableName, *string* $schemaName, *string* $columnName) + +Drops a column from a table + + + +public *boolean* **addIndex** (*string* $tableName, *string* $schemaName, *DbIndex* $index) + +Adds an index to a table + + + +public *boolean* **dropIndex** (*string* $tableName, *string* $schemaName, *string* $indexName) + +Drop an index from a table + + + +public *boolean* **addPrimaryKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) + +Adds a primary key to a table + + + +public *boolean* **dropPrimaryKey** (*string* $tableName, *string* $schemaName) + +Drops primary key from a table + + + +public *boolean true* **addForeignKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Reference ` $reference) + +Adds a foreign key to a table + + + +public *boolean true* **dropForeignKey** (*string* $tableName, *string* $schemaName, *string* $referenceName) + +Drops a foreign key from a table + + + +public *string* **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) + +Returns the SQL column definition from a column + + + +public *array* **listTables** (*string* $schemaName) + +List all tables on a database print_r($connection->listTables("blog") ?> + + + +public *string* **getDescriptor** () + +Return descriptor used to connect to the active database + + + +public *string* **getConnectionId** () + +Gets the active connection unique identifier + + + +public *string* **getSQLStatement** () + +Active SQL statement in the object + + + +public *string* **getRealSQLStatement** () + +Active SQL statement in the object without replace bound paramters + + + +public *array* **getSQLVariables** () + +Active SQL statement in the object + + + +public *array* **getSQLBindTypes** () + +Active SQL statement in the object + + + +public *string* **getType** () + +Returns type of database system the adapter is used for + + + +public *string* **getDialectType** () + +Returns the name of the dialect used + + + +public :doc:`Phalcon\\Db\\Dialect ` **getDialect** () + +Returns internal dialect instance + + + diff --git a/zh/api/Phalcon_Db_Adapter_Pdo.rst b/zh/api/Phalcon_Db_Adapter_Pdo.rst new file mode 100644 index 000000000000..3de250db1125 --- /dev/null +++ b/zh/api/Phalcon_Db_Adapter_Pdo.rst @@ -0,0 +1,469 @@ +Class **Phalcon\\Db\\Adapter\\Pdo** +=================================== + +*extends* :doc:`Phalcon\\Db ` + +Phalcon\\Db\\Adapter\\Pdo is the Phalcon\\Db that internally uses PDO to connect to a database + +.. code-block:: php + + '192.168.0.11', + 'username' => 'sigma', + 'password' => 'secret', + 'dbname' => 'blog', + 'port' => '3306', + )); + + + +Constants +--------- + +*integer* **FETCH_ASSOC** + +*integer* **FETCH_BOTH** + +*integer* **FETCH_NUM** + +Methods +--------- + +public **__construct** (*array* $descriptor) + +Constructor for Phalcon\\Db\\Adapter\\Pdo + + + +public *boolean* **connect** (*array* $descriptor) + +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection + + + +protected *PDOStatement* **_executePrepared** () + +Executes a prepared statement binding + + + +public :doc:`Phalcon\\Db\\Result\\Pdo ` **query** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server return rows + +.. code-block:: php + + query("SELECT * FROM robots WHERE type='mechanical'"); $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + + + +public *boolean* **execute** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don't return any row + +.. code-block:: php + + execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); + $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + + + + +public *int* **affectedRows** () + +Returns the number of affected rows by the last INSERT/UPDATE/DELETE repoted by the database system + +.. code-block:: php + + query("DELETE FROM robots"); + echo $connection->affectedRows(), ' were deleted'; + + + + +public *boolean* **close** () + +Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\\Db\\Pool + + + +public *string* **escapeString** (*string* $str) + +Escapes a value to avoid SQL injections + + + +public **bindParams** (*unknown* $sqlStatement, *array* $params) + +Bind params to a SQL statement + + + +public *array* **convertBoundParams** (*string* $sql, *array* $params) + +Converts bound params like :name: or ?1 into ? bind params + + + +public *int* **lastInsertId** (*string* $sequenceName) + +Returns insert id for the auto_increment column inserted in the last SQL statement + + + +public *boolean* **begin** () + +Starts a transaction in the connection + + + +public *boolean* **rollback** () + +Rollbacks the active transaction in the connection + + + +public *boolean* **commit** () + +Commits the active transaction in the connection + + + +public *boolean* **isUnderTransaction** () + +Checks whether connection is under database transaction + + + +public *PDO* **getInternalHandler** () + +Return internal PDO handler + + + +public :doc:`Phalcon\\Db\\Index ` [] **describeIndexes** (*string* $table, *string* $schema) + +Lists table indexes + + + +public :doc:`Phalcon\\Db\\Reference ` [] **describeReferences** (*string* $table, *string* $schema) + +Lists table references + + + +public *array* **tableOptions** (*string* $tableName, *string* $schemaName) + +Gets creation options from a table + + + +public :doc:`Phalcon\\Db\\RawValue ` **getDefaultIdValue** () + +Return the default identity value to insert in an identity column + + + +public *boolean* **supportSequences** () + +Check whether the database system requires a sequence to produce auto-numeric values + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\Db + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Db + +Returns the internal event manager + + + +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Returns the first row in a SQL query result + +.. code-block:: php + + fecthOne("SELECT * FROM robots"); + print_r($robot); + + //Getting first robot with associative indexes only + $robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + print_r($robot); + + + + +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Dumps the complete result of a query into an array + +.. code-block:: php + + fetchAll("SELECT * FROM robots"); + foreach($robots as $robot){ + print_r($robot); + } + + //Getting all robots with associative indexes only + $robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + foreach($robots as $robot){ + print_r($robot); + } + + + + +public *boolean* **insert** (*string* $table, *array* $values, *array* $fields, *array* $dataTypes) inherited from Phalcon\\Db + +Inserts data into a table using custom RBDM SQL syntax + +.. code-block:: php + + insert( + "robots", + array("Astro Boy", 1952), + array("name", "year") + ); + + //Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + + + + +public *boolean* **update** (*string* $table, *array* $fields, *array* $values, *string* $whereCondition, *array* $dataTypes) inherited from Phalcon\\Db + +Updates data on a table using custom RBDM SQL syntax + +.. code-block:: php + + update( + "robots", + array("name") + array("New Astro Boy"), + "id = 101" + ); + + //Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + + + +public *boolean* **delete** (*string* $table, *string* $whereCondition, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db + +Deletes data from a table using custom RBDM SQL syntax + +.. code-block:: php + + delete( + "robots", + "id = 101" + ); + + //Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public *string* **getColumnList** (*array* $columnList) inherited from Phalcon\\Db + +Gets a list of columns + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db + +Appends a LIMIT clause to $sqlQuery argument $connection->limit("SELECT * FROM robots", 5); + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.table $connection->tableExists("blog", "posts") + + + +public *string* **viewExists** (*string* $viewName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.view $connection->viewExists("active_users", "posts") + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *boolean* **createTable** (*string* $tableName, *string* $schemaName, *array* $definition) inherited from Phalcon\\Db + +Creates a table using MySQL SQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) inherited from Phalcon\\Db + +Drops a table from a schema/database + + + +public *boolean* **addColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Adds a column to a table + + + +public *boolean* **modifyColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Modifies a table column based on a definition + + + +public *boolean* **dropColumn** (*string* $tableName, *string* $schemaName, *string* $columnName) inherited from Phalcon\\Db + +Drops a column from a table + + + +public *boolean* **addIndex** (*string* $tableName, *string* $schemaName, *DbIndex* $index) inherited from Phalcon\\Db + +Adds an index to a table + + + +public *boolean* **dropIndex** (*string* $tableName, *string* $schemaName, *string* $indexName) inherited from Phalcon\\Db + +Drop an index from a table + + + +public *boolean* **addPrimaryKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) inherited from Phalcon\\Db + +Adds a primary key to a table + + + +public *boolean* **dropPrimaryKey** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Drops primary key from a table + + + +public *boolean true* **addForeignKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Reference ` $reference) inherited from Phalcon\\Db + +Adds a foreign key to a table + + + +public *boolean true* **dropForeignKey** (*string* $tableName, *string* $schemaName, *string* $referenceName) inherited from Phalcon\\Db + +Drops a foreign key from a table + + + +public *string* **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Returns the SQL column definition from a column + + + +public *array* **listTables** (*string* $schemaName) inherited from Phalcon\\Db + +List all tables on a database print_r($connection->listTables("blog") ?> + + + +public *string* **getDescriptor** () inherited from Phalcon\\Db + +Return descriptor used to connect to the active database + + + +public *string* **getConnectionId** () inherited from Phalcon\\Db + +Gets the active connection unique identifier + + + +public *string* **getSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getRealSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object without replace bound paramters + + + +public *array* **getSQLVariables** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *array* **getSQLBindTypes** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getType** () inherited from Phalcon\\Db + +Returns type of database system the adapter is used for + + + +public *string* **getDialectType** () inherited from Phalcon\\Db + +Returns the name of the dialect used + + + +public :doc:`Phalcon\\Db\\Dialect ` **getDialect** () inherited from Phalcon\\Db + +Returns internal dialect instance + + + diff --git a/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst b/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst new file mode 100755 index 000000000000..0c7488339491 --- /dev/null +++ b/zh/api/Phalcon_Db_Adapter_Pdo_Mysql.rst @@ -0,0 +1,477 @@ +Class **Phalcon\\Db\\Adapter\\Pdo\\Mysql** +========================================== + +*extends* :doc:`Phalcon\\Db\\Adapter\\Pdo ` + +Specific functions for the Mysql database system + +.. code-block:: php + + "192.168.0.11", + "dbname" => "blog", + "port" => 3306, + "username" => "sigma", + "password" => "secret" + ); + + $connection = new Phalcon\Db\Adapter\Pdo\Mysql($config); + + + +Constants +--------- + +*integer* **FETCH_ASSOC** + +*integer* **FETCH_BOTH** + +*integer* **FETCH_NUM** + +Methods +--------- + +public :doc:`Phalcon\\Db\\Column ` [] **describeColumns** (*string* $table, *string* $schema) + +Returns an array of Phalcon\\Db\\Column objects describing a table print_r($connection->describeColumns("posts")); ?> + + + +public **__construct** (*array* $descriptor) inherited from Phalcon\\Db\\Adapter\\Pdo + +Constructor for Phalcon\\Db\\Adapter\\Pdo + + + +public *boolean* **connect** (*array* $descriptor) inherited from Phalcon\\Db\\Adapter\\Pdo + +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection + + + +protected *PDOStatement* **_executePrepared** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Executes a prepared statement binding + + + +public :doc:`Phalcon\\Db\\Result\\Pdo ` **query** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server return rows + +.. code-block:: php + + query("SELECT * FROM robots WHERE type='mechanical'"); $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + + + +public *boolean* **execute** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don't return any row + +.. code-block:: php + + execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); + $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + + + + +public *int* **affectedRows** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Returns the number of affected rows by the last INSERT/UPDATE/DELETE repoted by the database system + +.. code-block:: php + + query("DELETE FROM robots"); + echo $connection->affectedRows(), ' were deleted'; + + + + +public *boolean* **close** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\\Db\\Pool + + + +public *string* **escapeString** (*string* $str) inherited from Phalcon\\Db\\Adapter\\Pdo + +Escapes a value to avoid SQL injections + + + +public **bindParams** (*unknown* $sqlStatement, *array* $params) inherited from Phalcon\\Db\\Adapter\\Pdo + +Bind params to a SQL statement + + + +public *array* **convertBoundParams** (*string* $sql, *array* $params) inherited from Phalcon\\Db\\Adapter\\Pdo + +Converts bound params like :name: or ?1 into ? bind params + + + +public *int* **lastInsertId** (*string* $sequenceName) inherited from Phalcon\\Db\\Adapter\\Pdo + +Returns insert id for the auto_increment column inserted in the last SQL statement + + + +public *boolean* **begin** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Starts a transaction in the connection + + + +public *boolean* **rollback** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Rollbacks the active transaction in the connection + + + +public *boolean* **commit** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Commits the active transaction in the connection + + + +public *boolean* **isUnderTransaction** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Checks whether connection is under database transaction + + + +public *PDO* **getInternalHandler** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Return internal PDO handler + + + +public :doc:`Phalcon\\Db\\Index ` [] **describeIndexes** (*string* $table, *string* $schema) inherited from Phalcon\\Db\\Adapter\\Pdo + +Lists table indexes + + + +public :doc:`Phalcon\\Db\\Reference ` [] **describeReferences** (*string* $table, *string* $schema) inherited from Phalcon\\Db\\Adapter\\Pdo + +Lists table references + + + +public *array* **tableOptions** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db\\Adapter\\Pdo + +Gets creation options from a table + + + +public :doc:`Phalcon\\Db\\RawValue ` **getDefaultIdValue** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Return the default identity value to insert in an identity column + + + +public *boolean* **supportSequences** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Check whether the database system requires a sequence to produce auto-numeric values + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\Db + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Db + +Returns the internal event manager + + + +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Returns the first row in a SQL query result + +.. code-block:: php + + fecthOne("SELECT * FROM robots"); + print_r($robot); + + //Getting first robot with associative indexes only + $robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + print_r($robot); + + + + +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Dumps the complete result of a query into an array + +.. code-block:: php + + fetchAll("SELECT * FROM robots"); + foreach($robots as $robot){ + print_r($robot); + } + + //Getting all robots with associative indexes only + $robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + foreach($robots as $robot){ + print_r($robot); + } + + + + +public *boolean* **insert** (*string* $table, *array* $values, *array* $fields, *array* $dataTypes) inherited from Phalcon\\Db + +Inserts data into a table using custom RBDM SQL syntax + +.. code-block:: php + + insert( + "robots", + array("Astro Boy", 1952), + array("name", "year") + ); + + //Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + + + + +public *boolean* **update** (*string* $table, *array* $fields, *array* $values, *string* $whereCondition, *array* $dataTypes) inherited from Phalcon\\Db + +Updates data on a table using custom RBDM SQL syntax + +.. code-block:: php + + update( + "robots", + array("name") + array("New Astro Boy"), + "id = 101" + ); + + //Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + + + +public *boolean* **delete** (*string* $table, *string* $whereCondition, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db + +Deletes data from a table using custom RBDM SQL syntax + +.. code-block:: php + + delete( + "robots", + "id = 101" + ); + + //Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public *string* **getColumnList** (*array* $columnList) inherited from Phalcon\\Db + +Gets a list of columns + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db + +Appends a LIMIT clause to $sqlQuery argument $connection->limit("SELECT * FROM robots", 5); + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.table $connection->tableExists("blog", "posts") + + + +public *string* **viewExists** (*string* $viewName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.view $connection->viewExists("active_users", "posts") + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *boolean* **createTable** (*string* $tableName, *string* $schemaName, *array* $definition) inherited from Phalcon\\Db + +Creates a table using MySQL SQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) inherited from Phalcon\\Db + +Drops a table from a schema/database + + + +public *boolean* **addColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Adds a column to a table + + + +public *boolean* **modifyColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Modifies a table column based on a definition + + + +public *boolean* **dropColumn** (*string* $tableName, *string* $schemaName, *string* $columnName) inherited from Phalcon\\Db + +Drops a column from a table + + + +public *boolean* **addIndex** (*string* $tableName, *string* $schemaName, *DbIndex* $index) inherited from Phalcon\\Db + +Adds an index to a table + + + +public *boolean* **dropIndex** (*string* $tableName, *string* $schemaName, *string* $indexName) inherited from Phalcon\\Db + +Drop an index from a table + + + +public *boolean* **addPrimaryKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) inherited from Phalcon\\Db + +Adds a primary key to a table + + + +public *boolean* **dropPrimaryKey** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Drops primary key from a table + + + +public *boolean true* **addForeignKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Reference ` $reference) inherited from Phalcon\\Db + +Adds a foreign key to a table + + + +public *boolean true* **dropForeignKey** (*string* $tableName, *string* $schemaName, *string* $referenceName) inherited from Phalcon\\Db + +Drops a foreign key from a table + + + +public *string* **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Returns the SQL column definition from a column + + + +public *array* **listTables** (*string* $schemaName) inherited from Phalcon\\Db + +List all tables on a database print_r($connection->listTables("blog") ?> + + + +public *string* **getDescriptor** () inherited from Phalcon\\Db + +Return descriptor used to connect to the active database + + + +public *string* **getConnectionId** () inherited from Phalcon\\Db + +Gets the active connection unique identifier + + + +public *string* **getSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getRealSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object without replace bound paramters + + + +public *array* **getSQLVariables** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *array* **getSQLBindTypes** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getType** () inherited from Phalcon\\Db + +Returns type of database system the adapter is used for + + + +public *string* **getDialectType** () inherited from Phalcon\\Db + +Returns the name of the dialect used + + + +public :doc:`Phalcon\\Db\\Dialect ` **getDialect** () inherited from Phalcon\\Db + +Returns internal dialect instance + + + diff --git a/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst b/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst new file mode 100755 index 000000000000..65085c39b310 --- /dev/null +++ b/zh/api/Phalcon_Db_Adapter_Pdo_Postgresql.rst @@ -0,0 +1,476 @@ +Class **Phalcon\\Db\\Adapter\\Pdo\\Postgresql** +=============================================== + +*extends* :doc:`Phalcon\\Db\\Adapter\\Pdo ` + +Specific functions for the Postgresql database system + +.. code-block:: php + + "192.168.0.11", + "dbname" => "blog", + "username" => "postgres", + "password" => "" + ); + + $connection = new Phalcon\Db\Adapter\Pdo\Postgresql($config); + + + +Constants +--------- + +*integer* **FETCH_ASSOC** + +*integer* **FETCH_BOTH** + +*integer* **FETCH_NUM** + +Methods +--------- + +public *boolean* **connect** (*array* $descriptor) + +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. Support set search_path after connectted if schema is specified in config. + + + +public :doc:`Phalcon\\Db\\Column ` [] **describeColumns** (*string* $table, *string* $schema) + +Returns an array of Phalcon\\Db\\Column objects describing a table print_r($connection->describeColumns("posts")); ?> + + + +public :doc:`Phalcon\\Db\\RawValue ` **getDefaultIdValue** () + +Return the default identity value to insert in an identity column + + + +public *boolean* **supportSequences** () + +Check whether the database system requires a sequence to produce auto-numeric values + + + +public **__construct** (*array* $descriptor) inherited from Phalcon\\Db\\Adapter\\Pdo + +Constructor for Phalcon\\Db\\Adapter\\Pdo + + + +protected *PDOStatement* **_executePrepared** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Executes a prepared statement binding + + + +public :doc:`Phalcon\\Db\\Result\\Pdo ` **query** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server return rows + +.. code-block:: php + + query("SELECT * FROM robots WHERE type='mechanical'"); $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + + + +public *boolean* **execute** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don't return any row + +.. code-block:: php + + execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); + $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + + + + +public *int* **affectedRows** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Returns the number of affected rows by the last INSERT/UPDATE/DELETE repoted by the database system + +.. code-block:: php + + query("DELETE FROM robots"); + echo $connection->affectedRows(), ' were deleted'; + + + + +public *boolean* **close** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\\Db\\Pool + + + +public *string* **escapeString** (*string* $str) inherited from Phalcon\\Db\\Adapter\\Pdo + +Escapes a value to avoid SQL injections + + + +public **bindParams** (*unknown* $sqlStatement, *array* $params) inherited from Phalcon\\Db\\Adapter\\Pdo + +Bind params to a SQL statement + + + +public *array* **convertBoundParams** (*string* $sql, *array* $params) inherited from Phalcon\\Db\\Adapter\\Pdo + +Converts bound params like :name: or ?1 into ? bind params + + + +public *int* **lastInsertId** (*string* $sequenceName) inherited from Phalcon\\Db\\Adapter\\Pdo + +Returns insert id for the auto_increment column inserted in the last SQL statement + + + +public *boolean* **begin** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Starts a transaction in the connection + + + +public *boolean* **rollback** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Rollbacks the active transaction in the connection + + + +public *boolean* **commit** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Commits the active transaction in the connection + + + +public *boolean* **isUnderTransaction** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Checks whether connection is under database transaction + + + +public *PDO* **getInternalHandler** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Return internal PDO handler + + + +public :doc:`Phalcon\\Db\\Index ` [] **describeIndexes** (*string* $table, *string* $schema) inherited from Phalcon\\Db\\Adapter\\Pdo + +Lists table indexes + + + +public :doc:`Phalcon\\Db\\Reference ` [] **describeReferences** (*string* $table, *string* $schema) inherited from Phalcon\\Db\\Adapter\\Pdo + +Lists table references + + + +public *array* **tableOptions** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db\\Adapter\\Pdo + +Gets creation options from a table + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\Db + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Db + +Returns the internal event manager + + + +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Returns the first row in a SQL query result + +.. code-block:: php + + fecthOne("SELECT * FROM robots"); + print_r($robot); + + //Getting first robot with associative indexes only + $robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + print_r($robot); + + + + +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Dumps the complete result of a query into an array + +.. code-block:: php + + fetchAll("SELECT * FROM robots"); + foreach($robots as $robot){ + print_r($robot); + } + + //Getting all robots with associative indexes only + $robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + foreach($robots as $robot){ + print_r($robot); + } + + + + +public *boolean* **insert** (*string* $table, *array* $values, *array* $fields, *array* $dataTypes) inherited from Phalcon\\Db + +Inserts data into a table using custom RBDM SQL syntax + +.. code-block:: php + + insert( + "robots", + array("Astro Boy", 1952), + array("name", "year") + ); + + //Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + + + + +public *boolean* **update** (*string* $table, *array* $fields, *array* $values, *string* $whereCondition, *array* $dataTypes) inherited from Phalcon\\Db + +Updates data on a table using custom RBDM SQL syntax + +.. code-block:: php + + update( + "robots", + array("name") + array("New Astro Boy"), + "id = 101" + ); + + //Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + + + +public *boolean* **delete** (*string* $table, *string* $whereCondition, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db + +Deletes data from a table using custom RBDM SQL syntax + +.. code-block:: php + + delete( + "robots", + "id = 101" + ); + + //Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public *string* **getColumnList** (*array* $columnList) inherited from Phalcon\\Db + +Gets a list of columns + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db + +Appends a LIMIT clause to $sqlQuery argument $connection->limit("SELECT * FROM robots", 5); + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.table $connection->tableExists("blog", "posts") + + + +public *string* **viewExists** (*string* $viewName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.view $connection->viewExists("active_users", "posts") + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *boolean* **createTable** (*string* $tableName, *string* $schemaName, *array* $definition) inherited from Phalcon\\Db + +Creates a table using MySQL SQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) inherited from Phalcon\\Db + +Drops a table from a schema/database + + + +public *boolean* **addColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Adds a column to a table + + + +public *boolean* **modifyColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Modifies a table column based on a definition + + + +public *boolean* **dropColumn** (*string* $tableName, *string* $schemaName, *string* $columnName) inherited from Phalcon\\Db + +Drops a column from a table + + + +public *boolean* **addIndex** (*string* $tableName, *string* $schemaName, *DbIndex* $index) inherited from Phalcon\\Db + +Adds an index to a table + + + +public *boolean* **dropIndex** (*string* $tableName, *string* $schemaName, *string* $indexName) inherited from Phalcon\\Db + +Drop an index from a table + + + +public *boolean* **addPrimaryKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) inherited from Phalcon\\Db + +Adds a primary key to a table + + + +public *boolean* **dropPrimaryKey** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Drops primary key from a table + + + +public *boolean true* **addForeignKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Reference ` $reference) inherited from Phalcon\\Db + +Adds a foreign key to a table + + + +public *boolean true* **dropForeignKey** (*string* $tableName, *string* $schemaName, *string* $referenceName) inherited from Phalcon\\Db + +Drops a foreign key from a table + + + +public *string* **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Returns the SQL column definition from a column + + + +public *array* **listTables** (*string* $schemaName) inherited from Phalcon\\Db + +List all tables on a database print_r($connection->listTables("blog") ?> + + + +public *string* **getDescriptor** () inherited from Phalcon\\Db + +Return descriptor used to connect to the active database + + + +public *string* **getConnectionId** () inherited from Phalcon\\Db + +Gets the active connection unique identifier + + + +public *string* **getSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getRealSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object without replace bound paramters + + + +public *array* **getSQLVariables** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *array* **getSQLBindTypes** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getType** () inherited from Phalcon\\Db + +Returns type of database system the adapter is used for + + + +public *string* **getDialectType** () inherited from Phalcon\\Db + +Returns the name of the dialect used + + + +public :doc:`Phalcon\\Db\\Dialect ` **getDialect** () inherited from Phalcon\\Db + +Returns internal dialect instance + + + diff --git a/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst b/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst new file mode 100644 index 000000000000..0b638dbc92a4 --- /dev/null +++ b/zh/api/Phalcon_Db_Adapter_Pdo_Sqlite.rst @@ -0,0 +1,473 @@ +Class **Phalcon\\Db\\Adapter\\Pdo\\Sqlite** +=========================================== + +*extends* :doc:`Phalcon\\Db\\Adapter\\Pdo ` + +Specific functions for the Sqlite database system + +.. code-block:: php + + "/tmp/test.sqlite" + ); + + $connection = new Phalcon\Db\Adapter\Pdo\Sqlite($config); + + + +Constants +--------- + +*integer* **FETCH_ASSOC** + +*integer* **FETCH_BOTH** + +*integer* **FETCH_NUM** + +Methods +--------- + +public *boolean* **connect** (*array* $descriptor) + +This method is automatically called in Phalcon\\Db\\Adapter\\Pdo constructor. Call it when you need to restore a database connection. + + + +public :doc:`Phalcon\\Db\\Column ` [] **describeColumns** (*string* $table, *string* $schema) + +Returns an array of Phalcon\\Db\\Column objects describing a table print_r($connection->describeColumns("posts")); ?> + + + +public :doc:`Phalcon\\Db\\Index ` [] **describeIndexes** (*string* $table, *string* $schema) + +Lists table indexes + + + +public :doc:`Phalcon\\Db\\Reference ` [] **describeReferences** (*string* $table, *string* $schema) + +Lists table references + + + +public **__construct** (*array* $descriptor) inherited from Phalcon\\Db\\Adapter\\Pdo + +Constructor for Phalcon\\Db\\Adapter\\Pdo + + + +protected *PDOStatement* **_executePrepared** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Executes a prepared statement binding + + + +public :doc:`Phalcon\\Db\\Result\\Pdo ` **query** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server return rows + +.. code-block:: php + + query("SELECT * FROM robots WHERE type='mechanical'"); $resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical")); + + + +public *boolean* **execute** (*string* $sqlStatement, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db\\Adapter\\Pdo + +Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server don't return any row + +.. code-block:: php + + execute("INSERT INTO robots VALUES (1, 'Astro Boy')"); + $success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy')); + + + + +public *int* **affectedRows** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Returns the number of affected rows by the last INSERT/UPDATE/DELETE repoted by the database system + +.. code-block:: php + + query("DELETE FROM robots"); + echo $connection->affectedRows(), ' were deleted'; + + + + +public *boolean* **close** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Closes active connection returning success. Phalcon automatically closes and destroys active connections within Phalcon\\Db\\Pool + + + +public *string* **escapeString** (*string* $str) inherited from Phalcon\\Db\\Adapter\\Pdo + +Escapes a value to avoid SQL injections + + + +public **bindParams** (*unknown* $sqlStatement, *array* $params) inherited from Phalcon\\Db\\Adapter\\Pdo + +Bind params to a SQL statement + + + +public *array* **convertBoundParams** (*string* $sql, *array* $params) inherited from Phalcon\\Db\\Adapter\\Pdo + +Converts bound params like :name: or ?1 into ? bind params + + + +public *int* **lastInsertId** (*string* $sequenceName) inherited from Phalcon\\Db\\Adapter\\Pdo + +Returns insert id for the auto_increment column inserted in the last SQL statement + + + +public *boolean* **begin** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Starts a transaction in the connection + + + +public *boolean* **rollback** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Rollbacks the active transaction in the connection + + + +public *boolean* **commit** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Commits the active transaction in the connection + + + +public *boolean* **isUnderTransaction** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Checks whether connection is under database transaction + + + +public *PDO* **getInternalHandler** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Return internal PDO handler + + + +public *array* **tableOptions** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db\\Adapter\\Pdo + +Gets creation options from a table + + + +public :doc:`Phalcon\\Db\\RawValue ` **getDefaultIdValue** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Return the default identity value to insert in an identity column + + + +public *boolean* **supportSequences** () inherited from Phalcon\\Db\\Adapter\\Pdo + +Check whether the database system requires a sequence to produce auto-numeric values + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\Db + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Db + +Returns the internal event manager + + + +public *array* **fetchOne** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Returns the first row in a SQL query result + +.. code-block:: php + + fecthOne("SELECT * FROM robots"); + print_r($robot); + + //Getting first robot with associative indexes only + $robot = $connection->fecthOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + print_r($robot); + + + + +public *array* **fetchAll** (*string* $sqlQuery, *int* $fetchMode) inherited from Phalcon\\Db + +Dumps the complete result of a query into an array + +.. code-block:: php + + fetchAll("SELECT * FROM robots"); + foreach($robots as $robot){ + print_r($robot); + } + + //Getting all robots with associative indexes only + $robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC); + foreach($robots as $robot){ + print_r($robot); + } + + + + +public *boolean* **insert** (*string* $table, *array* $values, *array* $fields, *array* $dataTypes) inherited from Phalcon\\Db + +Inserts data into a table using custom RBDM SQL syntax + +.. code-block:: php + + insert( + "robots", + array("Astro Boy", 1952), + array("name", "year") + ); + + //Next SQL sentence is sent to the database system + INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952); + + + + +public *boolean* **update** (*string* $table, *array* $fields, *array* $values, *string* $whereCondition, *array* $dataTypes) inherited from Phalcon\\Db + +Updates data on a table using custom RBDM SQL syntax + +.. code-block:: php + + update( + "robots", + array("name") + array("New Astro Boy"), + "id = 101" + ); + + //Next SQL sentence is sent to the database system + UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101 + + + + +public *boolean* **delete** (*string* $table, *string* $whereCondition, *array* $placeholders, *array* $dataTypes) inherited from Phalcon\\Db + +Deletes data from a table using custom RBDM SQL syntax + +.. code-block:: php + + delete( + "robots", + "id = 101" + ); + + //Next SQL sentence is generated + DELETE FROM `robots` WHERE `id` = 101 + + + + +public *string* **getColumnList** (*array* $columnList) inherited from Phalcon\\Db + +Gets a list of columns + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db + +Appends a LIMIT clause to $sqlQuery argument $connection->limit("SELECT * FROM robots", 5); + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.table $connection->tableExists("blog", "posts") + + + +public *string* **viewExists** (*string* $viewName, *string* $schemaName) inherited from Phalcon\\Db + +Generates SQL checking for the existence of a schema.view $connection->viewExists("active_users", "posts") + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *boolean* **createTable** (*string* $tableName, *string* $schemaName, *array* $definition) inherited from Phalcon\\Db + +Creates a table using MySQL SQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) inherited from Phalcon\\Db + +Drops a table from a schema/database + + + +public *boolean* **addColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Adds a column to a table + + + +public *boolean* **modifyColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Modifies a table column based on a definition + + + +public *boolean* **dropColumn** (*string* $tableName, *string* $schemaName, *string* $columnName) inherited from Phalcon\\Db + +Drops a column from a table + + + +public *boolean* **addIndex** (*string* $tableName, *string* $schemaName, *DbIndex* $index) inherited from Phalcon\\Db + +Adds an index to a table + + + +public *boolean* **dropIndex** (*string* $tableName, *string* $schemaName, *string* $indexName) inherited from Phalcon\\Db + +Drop an index from a table + + + +public *boolean* **addPrimaryKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) inherited from Phalcon\\Db + +Adds a primary key to a table + + + +public *boolean* **dropPrimaryKey** (*string* $tableName, *string* $schemaName) inherited from Phalcon\\Db + +Drops primary key from a table + + + +public *boolean true* **addForeignKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Reference ` $reference) inherited from Phalcon\\Db + +Adds a foreign key to a table + + + +public *boolean true* **dropForeignKey** (*string* $tableName, *string* $schemaName, *string* $referenceName) inherited from Phalcon\\Db + +Drops a foreign key from a table + + + +public *string* **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) inherited from Phalcon\\Db + +Returns the SQL column definition from a column + + + +public *array* **listTables** (*string* $schemaName) inherited from Phalcon\\Db + +List all tables on a database print_r($connection->listTables("blog") ?> + + + +public *string* **getDescriptor** () inherited from Phalcon\\Db + +Return descriptor used to connect to the active database + + + +public *string* **getConnectionId** () inherited from Phalcon\\Db + +Gets the active connection unique identifier + + + +public *string* **getSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getRealSQLStatement** () inherited from Phalcon\\Db + +Active SQL statement in the object without replace bound paramters + + + +public *array* **getSQLVariables** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *array* **getSQLBindTypes** () inherited from Phalcon\\Db + +Active SQL statement in the object + + + +public *string* **getType** () inherited from Phalcon\\Db + +Returns type of database system the adapter is used for + + + +public *string* **getDialectType** () inherited from Phalcon\\Db + +Returns the name of the dialect used + + + +public :doc:`Phalcon\\Db\\Dialect ` **getDialect** () inherited from Phalcon\\Db + +Returns internal dialect instance + + + diff --git a/zh/api/Phalcon_Db_Column.rst b/zh/api/Phalcon_Db_Column.rst new file mode 100755 index 000000000000..280265c60346 --- /dev/null +++ b/zh/api/Phalcon_Db_Column.rst @@ -0,0 +1,147 @@ +Class **Phalcon\\Db\\Column** +============================= + +Allows to define columns to be used on create or alter table operations + +.. code-block:: php + + Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true + )); + + //add column to existing table + $connection->addColumn("robots", null, $column); + + + +Constants +--------- + +*integer* **TYPE_INTEGER** + +*integer* **TYPE_DATE** + +*integer* **TYPE_VARCHAR** + +*integer* **TYPE_DECIMAL** + +*integer* **TYPE_DATETIME** + +*integer* **TYPE_CHAR** + +*integer* **TYPE_TEXT** + +*integer* **TYPE_FLOAT** + +*integer* **BIND_PARAM_NULL** + +*integer* **BIND_PARAM_INT** + +*integer* **BIND_PARAM_STR** + +*integer* **BIND_PARAM_DECIMAL** + +*integer* **BIND_SKIP** + +Methods +--------- + +public **__construct** (*string* $columnName, *array* $definition) + +Phalcon\\Db\\Column constructor + + + +public *string* **getSchemaName** () + +Returns schema's table related to column + + + +public *string* **getName** () + +Returns column name + + + +public *int* **getType** () + +Returns column type + + + +public *int* **getSize** () + +Returns column size + + + +public *int* **getScale** () + +Returns column scale + + + +public *boolean* **isUnsigned** () + +Returns true if number column is unsigned + + + +public *boolean* **isNotNull** () + +Not null + + + +public *boolean* **isPrimary** () + +Column is part of the primary key? + + + +public *boolean* **isAutoIncrement** () + +Auto-Increment + + + +public *boolean* **isNumeric** () + +Check whether column have an numeric type + + + +public *boolean* **isFirst** () + +Check whether column have first position in table + + + +public *string* **getAfterPosition** () + +Check whether field absolute to position in table + + + +public **getBindType** () + +Returns the type of bind handling + + + +public static **__set_state** (*unknown* $data) + +... + + diff --git a/zh/api/Phalcon_Db_Dialect.rst b/zh/api/Phalcon_Db_Dialect.rst new file mode 100644 index 000000000000..e7d717df37b4 --- /dev/null +++ b/zh/api/Phalcon_Db_Dialect.rst @@ -0,0 +1,33 @@ +Class **Phalcon\\Db\\Dialect** +============================== + +This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBM related syntax + + +Methods +--------- + +public *string* **limit** (*string* $sqlQuery, *int* $number) + +Generates the SQL for LIMIT clause + + + +public *string* **forUpdate** (*string* $sqlQuery) + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *string* **select** (*array* $definition) + +Builds a SELECT statement + + + diff --git a/zh/api/Phalcon_Db_Dialect_Mysql.rst b/zh/api/Phalcon_Db_Dialect_Mysql.rst new file mode 100755 index 000000000000..2bdc1949a1af --- /dev/null +++ b/zh/api/Phalcon_Db_Dialect_Mysql.rst @@ -0,0 +1,155 @@ +Class **Phalcon\\Db\\Dialect\\Mysql** +===================================== + +*extends* :doc:`Phalcon\\Db\\Dialect ` + +Generates database specific SQL for the MySQL RBDM + + +Methods +--------- + +public *string* **getColumnList** (*array* $columnList) + +Gets a list of columns + + + +public **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) + +Gets the column name in MySQL + + + +public *string* **addColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) + +Generates SQL to add a column to a table + + + +public *string* **modifyColumn** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Column ` $column) + +Generates SQL to modify a column in a table + + + +public *string* **dropColumn** (*string* $tableName, *string* $schemaName, *string* $columnName) + +Generates SQL to delete a column from a table + + + +public *string* **addIndex** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) + +Generates SQL to add an index to a table + + + +public *string* **dropIndex** (*string* $tableName, *string* $schemaName, *string* $indexName) + +Generates SQL to delete an index from a table + + + +public *string* **addPrimaryKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Index ` $index) + +Generates SQL to add the primary key to a table + + + +public *string* **dropPrimaryKey** (*string* $tableName, *string* $schemaName) + +Generates SQL to delete primary key from a table + + + +public *string* **addForeignKey** (*string* $tableName, *string* $schemaName, :doc:`Phalcon\\Db\\Reference ` $reference) + +Generates SQL to add an index to a table + + + +public *string* **dropForeignKey** (*string* $tableName, *string* $schemaName, *string* $referenceName) + +Generates SQL to delete a foreign key from a table + + + +protected *array* **_getTableOptions** () + +Generates SQL to add the table creation options + + + +public *string* **createTable** (*string* $tableName, *string* $schemaName, *array* $definition) + +Generates SQL to create a table in MySQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) + +Generates SQL to drop a table + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) + +Generates SQL checking for the existence of a schema.table echo $dialect->tableExists("posts", "blog") echo $dialect->tableExists("posts") + + + +public *string* **describeColumns** (*string* $table, *string* $schema) + +Generates SQL describing a table print_r($dialect->describeColumns("posts") ?> + + + +public *array* **listTables** (*string* $schemaName) + +List all tables on database print_r($dialect->listTables("blog") ?> + + + +public *string* **describeIndexes** (*string* $table, *string* $schema) + +Generates SQL to query indexes on a table + + + +public *string* **describeReferences** (*string* $table, *string* $schema) + +Generates SQL to query foreign keys on a table + + + +public *string* **tableOptions** (*string* $table, *string* $schema) + +Generates the SQL to describe the table creation options + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db\\Dialect + +Generates the SQL for LIMIT clause + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db\\Dialect + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db\\Dialect + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *string* **select** (*array* $definition) inherited from Phalcon\\Db\\Dialect + +Builds a SELECT statement + + + diff --git a/zh/api/Phalcon_Db_Dialect_Postgresql.rst b/zh/api/Phalcon_Db_Dialect_Postgresql.rst new file mode 100755 index 000000000000..0f47b3cd91b3 --- /dev/null +++ b/zh/api/Phalcon_Db_Dialect_Postgresql.rst @@ -0,0 +1,155 @@ +Class **Phalcon\\Db\\Dialect\\Postgresql** +========================================== + +*extends* :doc:`Phalcon\\Db\\Dialect ` + +Generates database specific SQL for the PostgreSQL RBDM + + +Methods +--------- + +public *string* **getColumnList** (*array* $columnList) + +Gets a list of columns + + + +public static **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) + +Gets the column name in PostgreSQL + + + +public static *string* **addColumn** () + +Generates SQL to add a column to a table + + + +public static *string* **modifyColumn** () + +Generates SQL to modify a column in a table + + + +public static *string* **dropColumn** () + +Generates SQL to delete a column from a table + + + +public static *string* **addIndex** () + +Generates SQL to add an index to a table + + + +public static *string* **dropIndex** () + +Generates SQL to delete an index from a table + + + +public static *string* **addPrimaryKey** () + +Generates SQL to add the primary key to a table + + + +public static *string* **dropPrimaryKey** () + +Generates SQL to delete primary key from a table + + + +public static *string* **addForeignKey** () + +Generates SQL to add an index to a table + + + +public static *string* **dropForeignKey** () + +Generates SQL to delete a foreign key from a table + + + +protected *array* **_getTableOptions** () + +Generates SQL to add the table creation options + + + +public *string* **createTable** () + +Generates SQL to create a table in PostgreSQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) + +Generates SQL to drop a table + + + +public static *string* **tableExists** (*string* $tableName, *string* $schemaName) + +Generates SQL checking for the existence of a schema.table echo $dialect->tableExists("posts", "blog") echo $dialect->tableExists("posts") + + + +public *string* **describeColumns** (*string* $table, *string* $schema) + +Generates a SQL describing a table print_r($dialect->describeColumns("posts") ?> + + + +public *array* **listTables** (*string* $schemaName) + +List all tables on database print_r($dialect->listTables("blog") ?> + + + +public *string* **describeIndexes** (*string* $table, *string* $schema) + +Generates SQL to query indexes on a table + + + +public *string* **describeReferences** (*string* $table, *string* $schema) + +Generates SQL to query foreign keys on a table + + + +public *string* **tableOptions** (*string* $table, *string* $schema) + +Generates the SQL to describe the table creation options + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db\\Dialect + +Generates the SQL for LIMIT clause + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db\\Dialect + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db\\Dialect + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *string* **select** (*array* $definition) inherited from Phalcon\\Db\\Dialect + +Builds a SELECT statement + + + diff --git a/zh/api/Phalcon_Db_Dialect_Sqlite.rst b/zh/api/Phalcon_Db_Dialect_Sqlite.rst new file mode 100644 index 000000000000..b55138e9f70e --- /dev/null +++ b/zh/api/Phalcon_Db_Dialect_Sqlite.rst @@ -0,0 +1,161 @@ +Class **Phalcon\\Db\\Dialect\\Sqlite** +====================================== + +*extends* :doc:`Phalcon\\Db\\Dialect ` + +Generates database specific SQL for the Sqlite RBDM + + +Methods +--------- + +public *string* **getColumnList** (*array* $columnList) + +Gets a list of columns + + + +public **getColumnDefinition** (:doc:`Phalcon\\Db\\Column ` $column) + +Gets the column name in Sqlite + + + +public *string* **addColumn** () + +Generates SQL to add a column to a table + + + +public *string* **modifyColumn** () + +Generates SQL to modify a column in a table + + + +public *string* **dropColumn** () + +Generates SQL to delete a column from a table + + + +public *string* **addIndex** () + +Generates SQL to add an index to a table + + + +public *string* **dropIndex** () + +Generates SQL to delete an index from a table + + + +public *string* **addPrimaryKey** () + +Generates SQL to add the primary key to a table + + + +public *string* **dropPrimaryKey** () + +Generates SQL to delete primary key from a table + + + +public *string* **addForeignKey** () + +Generates SQL to add an index to a table + + + +public *string* **dropForeignKey** () + +Generates SQL to delete a foreign key from a table + + + +protected *array* **_getTableOptions** () + +Generates SQL to add the table creation options + + + +public *string* **createTable** () + +Generates SQL to create a table in PostgreSQL + + + +public *boolean* **dropTable** (*string* $tableName, *string* $schemaName, *boolean* $ifExists) + +Generates SQL to drop a table + + + +public *string* **tableExists** (*string* $tableName, *string* $schemaName) + +Generates SQL checking for the existence of a schema.table echo $dialect->tableExists("posts", "blog") echo $dialect->tableExists("posts") + + + +public *string* **describeColumns** (*string* $table, *string* $schema) + +Generates a SQL describing a table print_r($dialect->describeColumns("posts") ?> + + + +public *array* **listTables** (*string* $schemaName) + +List all tables on database print_r($dialect->listTables("blog") ?> + + + +public *string* **describeIndexes** (*string* $table, *string* $schema) + +Generates SQL to query indexes on a table + + + +public *string* **describeIndex** (*string* $indexName) + +Generates SQL to query indexes detail on a table + + + +public *string* **describeReferences** (*string* $table, *string* $schema) + +Generates SQL to query foreign keys on a table + + + +public *string* **tableOptions** (*string* $table, *string* $schema) + +Generates the SQL to describe the table creation options + + + +public *string* **limit** (*string* $sqlQuery, *int* $number) inherited from Phalcon\\Db\\Dialect + +Generates the SQL for LIMIT clause + + + +public *string* **forUpdate** (*string* $sqlQuery) inherited from Phalcon\\Db\\Dialect + +Returns a SQL modified with a FOR UPDATE clause + + + +public *string* **sharedLock** (*string* $sqlQuery) inherited from Phalcon\\Db\\Dialect + +Returns a SQL modified with a LOCK IN SHARE MODE clause + + + +public *string* **select** (*array* $definition) inherited from Phalcon\\Db\\Dialect + +Builds a SELECT statement + + + diff --git a/zh/api/Phalcon_Db_Exception.rst b/zh/api/Phalcon_Db_Exception.rst new file mode 100755 index 000000000000..e5f661040078 --- /dev/null +++ b/zh/api/Phalcon_Db_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Db\\Exception** +================================ + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Db will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Db_Index.rst b/zh/api/Phalcon_Db_Index.rst new file mode 100755 index 000000000000..8d75825fc67f --- /dev/null +++ b/zh/api/Phalcon_Db_Index.rst @@ -0,0 +1,38 @@ +Class **Phalcon\\Db\\Index** +============================ + +Allows to define indexes to be used on tables. Indexes are a common way to enhance database performance. An index allows the database server to find and retrieve specific rows much faster than it could do without an index. + +.. code-block:: php + + ` **__set_state** (*array* $data) + +Restore a Phalcon\\Db\\Index object from export + + + diff --git a/zh/api/Phalcon_Db_Profiler.rst b/zh/api/Phalcon_Db_Profiler.rst new file mode 100755 index 000000000000..620ca8d9231f --- /dev/null +++ b/zh/api/Phalcon_Db_Profiler.rst @@ -0,0 +1,81 @@ +Class **Phalcon\\Db\\Profiler** +=============================== + +Instances of Phalcon\\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in miliseconds. This helps you to identify bottlenecks in your applications. + +.. code-block:: php + + setProfiler($profiler); + + $sql = "SELECT buyer_name, quantity, product_name + FROM buyers LEFT JOIN products ON + buyers.pid=products.id"; + + //Execute a SQL statement + $connection->query($sql); + + //Get the last profile in the profiler + $profile = $profiler->getLastProfile(); + + echo "SQL Statement: ", $profile->getSQLStatement(), "\n"; + echo "Start Time: ", $profile->getInitialTime(), "\n"; + echo "Final Time: ", $profile->getFinalTime(), "\n"; + echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n"; + + + +Methods +--------- + +public **__construct** () + +... + + +public :doc:`Phalcon\\Db\\Profiler ` **startProfile** (*string* $sqlStatement) + +Starts the profile of a SQL sentence + + + +public :doc:`Phalcon\\Db\\Profiler ` **stopProfile** () + +Stops the active profile + + + +public *integer* **getNumberTotalStatements** () + +Returns the total number of SQL statements processed + + + +public *double* **getTotalElapsedSeconds** () + +Returns the total time in seconds spent by the profiles + + + +public :doc:`Phalcon\\Db\\Profiler\\Item ` [] **getProfiles** () + +Returns all the processed profiles + + + +public :doc:`Phalcon\\Db\\Profiler ` **reset** () + +Resets the profiler, cleaning up all the profiles + + + +public :doc:`Phalcon\\Db\\Profiler\\Item ` **getLastProfile** () + +Returns the last profile executed in the profiler + + + diff --git a/zh/api/Phalcon_Db_Profiler_Item.rst b/zh/api/Phalcon_Db_Profiler_Item.rst new file mode 100755 index 000000000000..4e26d27eab5e --- /dev/null +++ b/zh/api/Phalcon_Db_Profiler_Item.rst @@ -0,0 +1,51 @@ +Class **Phalcon\\Db\\Profiler\\Item** +===================================== + +This class identifies each profile in a Phalcon\\Db\\Profiler + + +Methods +--------- + +public **setSQLStatement** (*string* $sqlStatement) + +Sets the SQL statement related to the profile + + + +public *string* **getSQLStatement** () + +Returns the SQL statement related to the profile + + + +public **setInitialTime** (*int* $initialTime) + +Sets the timestamp on when the profile started + + + +public **setFinalTime** (*int* $finalTime) + +Sets the timestamp on when the profile ended + + + +public *double* **getInitialTime** () + +Returns the initial time in milseconds on when the profile started + + + +public *double* **getFinalTime** () + +Returns the initial time in milseconds on when the profile ended + + + +public *double* **getTotalElapsedSeconds** () + +Returns the total time in seconds spent by the profile + + + diff --git a/zh/api/Phalcon_Db_RawValue.rst b/zh/api/Phalcon_Db_RawValue.rst new file mode 100755 index 000000000000..243bfc38eaf5 --- /dev/null +++ b/zh/api/Phalcon_Db_RawValue.rst @@ -0,0 +1,37 @@ +Class **Phalcon\\Db\\RawValue** +=============================== + +This class allows to insert/update raw data without quoting or formating. The next example shows how to use the MySQL now() function as a field value. + +.. code-block:: php + + email = 'andres@phalconphp.com'; + $subscriber->created_at = new Phalcon\Db\RawValue('now()'); + $subscriber->save(); + + + +Methods +--------- + +public **__construct** (*string* $value) + +Phalcon\\Db\\RawValue constructor + + + +public *string* **getValue** () + +Returns internal raw value without quoting or formating + + + +public **__toString** () + +Magic method __toString returns raw value without quoting or formating + + + diff --git a/zh/api/Phalcon_Db_Reference.rst b/zh/api/Phalcon_Db_Reference.rst new file mode 100755 index 000000000000..4d3f789843b7 --- /dev/null +++ b/zh/api/Phalcon_Db_Reference.rst @@ -0,0 +1,69 @@ +Class **Phalcon\\Db\\Reference** +================================ + +Allows to define reference constraints on tables + +.. code-block:: php + + "invoicing", + 'referencedTable' => "products", + 'columns' => array("product_type", "product_code"), + 'referencedColumns' => array("type", "code") + )); + + + +Methods +--------- + +public **__construct** (*string* $referenceName, *array* $definition) + +Phalcon\\Db\\Reference constructor + + + +public *string* **getName** () + +Gets the index name + + + +public *string* **getSchemaName** () + +Gets the schema where referenced table is + + + +public *string* **getReferencedSchema** () + +Gets the schema where referenced table is + + + +public *array* **getColumns** () + +Gets local columns which reference is based + + + +public *string* **getReferencedTable** () + +Gets the referenced table + + + +public *array* **getReferencedColumns** () + +Gets referenced columns + + + +public static :doc:`Phalcon\\Db\\Reference ` **__set_state** (*array* $data) + +Restore a Phalcon\\Db\\Reference object from export + + + diff --git a/zh/api/Phalcon_Db_Result_Pdo.rst b/zh/api/Phalcon_Db_Result_Pdo.rst new file mode 100644 index 000000000000..519d1ce7e82f --- /dev/null +++ b/zh/api/Phalcon_Db_Result_Pdo.rst @@ -0,0 +1,118 @@ +Class **Phalcon\\Db\\Result\\Pdo** +================================== + +Encapsulates the resultset internals + +.. code-block:: php + + query("SELECT * FROM robots ORDER BY name"); + $result->setFetchMode(Phalcon\Db::FETCH_NUM); + while($robot = $result->fetchArray()){ + print_r($robot); + } + + + +Methods +--------- + +public **__construct** (:doc:`Phalcon\\Db\\Adapter\\Pdo ` $connection, *PDOStatement* $result, *string* $sqlStatement, *array* $bindParams, *array* $bindTypes) + +Phalcon\\Db\\Result\\Pdo constructor + + + +public *boolean* **execute** () + +Allows to executes the statement again. Some database systems don't support scrollable cursors, So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining + + + +public *boolean* **fetchArray** () + +Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\\Db\\Result\\Pdo::setFetchMode + +.. code-block:: php + + query("SELECT * FROM robots ORDER BY name"); + $result->setFetchMode(Phalcon\Db::FETCH_NUM); + while($robot = $result->fetchArray()){ + print_r($robot); + } + + + + +public *array* **fetchAll** () + +Returns an array of arrays containing all the records in the result This method is affected by the active fetch flag set using Phalcon\\Db\\Result\\Pdo::setFetchMode + +.. code-block:: php + + query("SELECT * FROM robots ORDER BY name"); + $robots = $result->fetchAll(); + + + + +public *int* **numRows** () + +Gets number of rows returned by a resulset + +.. code-block:: php + + query("SELECT * FROM robots ORDER BY name"); + echo 'There are ', $result->numRows(), ' rows in the resulset'; + + + + +public **dataSeek** (*int* $number) + +Moves internal resulset cursor to another position letting us to fetch a certain row + +.. code-block:: php + + query("SELECT * FROM robots ORDER BY name"); + $result->dataSeek(2); // Move to third row on result + $row = $result->fetchArray(); // Fetch third row + + + + +public **setFetchMode** (*int* $fetchMode) + +Changes the fetching mode affecting Phalcon\\Db\\Result\\Pdo::fetchArray + +.. code-block:: php + + setFetchMode(Phalcon\Db::FETCH_NUM); + + //Return associative array without integer indexes + $result->setFetchMode(Phalcon\Db::FETCH_ASSOC); + + //Return associative array together with integer indexes + $result->setFetchMode(Phalcon\Db::FETCH_BOTH); + + + + +public *PDOStatement* **getInternalResult** () + +Gets the internal PDO result object + + + diff --git a/zh/api/Phalcon_Dispatcher.rst b/zh/api/Phalcon_Dispatcher.rst new file mode 100644 index 000000000000..1cc0d9740f08 --- /dev/null +++ b/zh/api/Phalcon_Dispatcher.rst @@ -0,0 +1,129 @@ +Class **Phalcon\\Dispatcher** +============================= + +This is the base class for Phalcon\\Mvc\\Dispatcher and Phalcon\\CLI\\Dispatcher + + +Constants +--------- + +*integer* **EXCEPTION_NO_DI** + +*integer* **EXCEPTION_CYCLIC_ROUTING** + +*integer* **EXCEPTION_HANDLER_NOT_FOUND** + +*integer* **EXCEPTION_INVALID_PARAMS** + +*integer* **EXCEPTION_ACTION_NOT_FOUND** + +Methods +--------- + +public **__construct** () + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public **setActionSuffix** (*string* $actionSuffix) + +Sets the default action suffix + + + +public **setDefaultNamespace** (*string* $namespace) + +Sets the default namespace + + + +public **setDefaultAction** (*string* $actionName) + +Sets the default action name + + + +public **setActionName** (*string* $actionName) + +Sets the action name to be dispatched + + + +public *string* **getActionName** () + +Gets last dispatched action name + + + +public **setParams** (*array* $params) + +Sets action params to be dispatched + + + +public *array* **getParams** () + +Gets action params + + + +public **setParam** (*mixed* $param, *mixed* $value) + +Set a param by its name or numeric index + + + +public *mixed* **getParam** (*mixed* $param, *string|array* $filters) + +Gets a param by its name or numeric index + + + +public *boolean* **isFinished** () + +Checks if the dispatch loop is finished or have more pendent controllers/tasks to disptach + + + +public *mixed* **getReturnedValue** () + +Returns value returned by the lastest dispatched action + + + +public *object* **dispatch** () + +Dispatches a handle action taking into account the routing parameters + + + +public **forward** (*array* $forward) + +Forwards the execution flow to another controller/action + + + diff --git a/zh/api/Phalcon_Escaper.rst b/zh/api/Phalcon_Escaper.rst new file mode 100644 index 000000000000..f36b27743dd1 --- /dev/null +++ b/zh/api/Phalcon_Escaper.rst @@ -0,0 +1,65 @@ +Class **Phalcon\\Escaper** +========================== + +Escapes different kinds of text securing them. By using this component you may prevent XSS attacks. This component only works with UTF-8. The PREG extension needs to be compiled with UTF-8 support. + +.. code-block:: php + + escapeCss("font-family: "); + echo $escaped; // font\2D family\3A \20 \3C Verdana\3E + + + +Methods +--------- + +public **setEnconding** (*string* $encoding) + +Sets the encoding to be used by the escaper + + + +public *string* **getEncoding** () + +Returns the internal encoding used by the escaper + + + +public **setHtmlQuoteType** (*unknown* $quoteType) + +Sets the HTML quoting type for htmlspecialchars + + + +public *string* **escapeHtml** (*string* $text) + +Escapes a HTML string. Internally uses htmlspeciarchars + + + +public **escapeHtmlAttr** (*unknown* $text) + +... + + +public *string* **cssSanitize** (*array* $matches) + +Sanitizes CSS strings converting non-alphanumeric chars to their hexadecimal representation + + + +public **escapeCss** (*string* $css) + +Escape CSS strings by replacing non-alphanumeric chars by their hexadecimal representation + + + +public *string* **escapeUrl** (*string* $url) + +Escapes a URL. Internally uses rawurlencode + + + diff --git a/zh/api/Phalcon_Escaper_Exception.rst b/zh/api/Phalcon_Escaper_Exception.rst new file mode 100644 index 000000000000..7a7578748a40 --- /dev/null +++ b/zh/api/Phalcon_Escaper_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Escaper\\Exception** +===================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Escaper will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Events_Event.rst b/zh/api/Phalcon_Events_Event.rst new file mode 100644 index 000000000000..5510defc5c9f --- /dev/null +++ b/zh/api/Phalcon_Events_Event.rst @@ -0,0 +1,45 @@ +Class **Phalcon\\Events\\Event** +================================ + +This class offers contextual information of a fired event in the EventsManager + + +Methods +--------- + +public **__construct** (*string* $type, *object* $source, *mixed* $data) + +Phalcon\\Events\\Event constructor + + + +public **setType** (*string* $eventType) + +Set the event's type + + + +public *string* **getType** () + +Returns the event's type + + + +public *object* **getSource** () + +Returns the event's source + + + +public **setData** (*string* $data) + +Set the event's data + + + +public *mixed* **getData** () + +Returns the event's data + + + diff --git a/zh/api/Phalcon_Events_Exception.rst b/zh/api/Phalcon_Events_Exception.rst new file mode 100644 index 000000000000..f1f49d5e8264 --- /dev/null +++ b/zh/api/Phalcon_Events_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Events\\Exception** +==================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Events will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Events_Manager.rst b/zh/api/Phalcon_Events_Manager.rst new file mode 100644 index 000000000000..277998637fd9 --- /dev/null +++ b/zh/api/Phalcon_Events_Manager.rst @@ -0,0 +1,33 @@ +Class **Phalcon\\Events\\Manager** +================================== + +Phalcon Events Manager, offers an easy way to intercept and manipulate, if needed, the normal flow of operation. With the EventsManager the developer can create hooks or plugins that will offer monitoring of data, manipulation, conditional execution and much more. + + +Methods +--------- + +public **attach** (*string* $eventType, *object* $handler) + +Attach a listener to the events manager + + + +public **dettachAll** (*unknown* $type) + +Removes all events from the EventsManager + + + +public *mixed* **fire** (*string* $eventType, *object* $source, *mixed* $data) + +Fires a event in the events manager causing that the acive listeners will be notified about it + + + +public *array* **getListeners** (*string* $type) + +Returns all the attached listeners of a certain type + + + diff --git a/zh/api/Phalcon_Exception.rst b/zh/api/Phalcon_Exception.rst new file mode 100755 index 000000000000..a0f0c5214ab2 --- /dev/null +++ b/zh/api/Phalcon_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Exception** +============================ + +*extends* Exception + +All framework exceptions should use or extend this exception + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Filter.rst b/zh/api/Phalcon_Filter.rst new file mode 100755 index 000000000000..d848af97d997 --- /dev/null +++ b/zh/api/Phalcon_Filter.rst @@ -0,0 +1,49 @@ +Class **Phalcon\\Filter** +========================= + +The Phalcon\\Filter component provides a set of commonly needed data filters. It provides object oriented wrappers to the php filter extension. Also allows the developer to define his/her own filters + +.. code-block:: php + + sanitize("some(one)@exa\\mple.com", "email"); // returns "someone@example.com" + $filter->sanitize("hello<<", "string"); // returns "hello" + $filter->sanitize("!100a019", "int"); // returns "100019" + $filter->sanitize("!100a019.01a", "float"); // returns "100019.01" + + + +Methods +--------- + +public **__construct** () + +... + + +public **add** (*string* $name, *callable* $handler) + +Adds a user-defined filter + + + +public *mixed* **sanitize** (*mixed* $value, *mixed* $filters) + +Sanizites a value with a specified single or set of filters + + + +protected *mixed* **_sanitize** () + +Internal sanizite wrapper to filter_var + + + +public *object[]* **getFilters** () + +Return the user-defined filters in the instance + + + diff --git a/zh/api/Phalcon_Filter_Exception.rst b/zh/api/Phalcon_Filter_Exception.rst new file mode 100644 index 000000000000..0d42cad5571a --- /dev/null +++ b/zh/api/Phalcon_Filter_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Filter\\Exception** +==================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Filter will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Flash.rst b/zh/api/Phalcon_Flash.rst new file mode 100755 index 000000000000..5ff3b2a5337e --- /dev/null +++ b/zh/api/Phalcon_Flash.rst @@ -0,0 +1,99 @@ +Class **Phalcon\\Flash** +======================== + +Shows HTML notifications related to different circumstances. Classes can be stylized using CSS + +.. code-block:: php + + success("The record was successfully deleted"); + $flash->error("Cannot open the file"); + + + +Methods +--------- + +public **__construct** (*array* $cssClasses) + +Phalcon\\Flash constructor + + + +public **setImplicitFlush** (*unknown* $implicitFlush) + +Set the if the output must be implictly flushed to the output or returned as string + + + +public **setAutomaticHtml** (*boolean* $automaticHtml) + +Set the if the output must be implictly formatted with HTML + + + +public **setCssClasses** (*array* $cssClasses) + +Set an array with CSS classes to format the messages + + + +public *string* **error** (*string* $message) + +Shows a HTML error message + +.. code-block:: php + + error('This is an error'); + + + + +public *string* **notice** (*string* $message) + +Shows a HTML notice/information message + +.. code-block:: php + + notice('This is an information'); + + + + +public *string* **success** (*string* $message) + +Shows a HTML success message + +.. code-block:: php + + success('The process was finished successfully'); + + + + +public *string* **warning** (*string* $message) + +Shows a HTML warning message + +.. code-block:: php + + warning('Hey, this is important'); + + + + +public **outputMessage** (*string* $type, *string* $message) + +Outputs a message formatting it with HTML + + + diff --git a/zh/api/Phalcon_Flash_Direct.rst b/zh/api/Phalcon_Flash_Direct.rst new file mode 100644 index 000000000000..f4d22c61a1c3 --- /dev/null +++ b/zh/api/Phalcon_Flash_Direct.rst @@ -0,0 +1,99 @@ +Class **Phalcon\\Flash\\Direct** +================================ + +*extends* :doc:`Phalcon\\Flash ` + +This is a variant of the Phalcon\\Flash that inmediately outputs any message passed to it + + +Methods +--------- + +public *string* **message** (*string* $type, *string* $message) + +Outputs a message + + + +public **__construct** (*array* $cssClasses) inherited from Phalcon\\Flash + +Phalcon\\Flash constructor + + + +public **setImplicitFlush** (*unknown* $implicitFlush) inherited from Phalcon\\Flash + +Set the if the output must be implictly flushed to the output or returned as string + + + +public **setAutomaticHtml** (*boolean* $automaticHtml) inherited from Phalcon\\Flash + +Set the if the output must be implictly formatted with HTML + + + +public **setCssClasses** (*array* $cssClasses) inherited from Phalcon\\Flash + +Set an array with CSS classes to format the messages + + + +public *string* **error** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML error message + +.. code-block:: php + + error('This is an error'); + + + + +public *string* **notice** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML notice/information message + +.. code-block:: php + + notice('This is an information'); + + + + +public *string* **success** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML success message + +.. code-block:: php + + success('The process was finished successfully'); + + + + +public *string* **warning** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML warning message + +.. code-block:: php + + warning('Hey, this is important'); + + + + +public **outputMessage** (*string* $type, *string* $message) inherited from Phalcon\\Flash + +Outputs a message formatting it with HTML + + + diff --git a/zh/api/Phalcon_Flash_Exception.rst b/zh/api/Phalcon_Flash_Exception.rst new file mode 100644 index 000000000000..0398287c8d61 --- /dev/null +++ b/zh/api/Phalcon_Flash_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Flash\\Exception** +=================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Flash will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Flash_Session.rst b/zh/api/Phalcon_Flash_Session.rst new file mode 100644 index 000000000000..e2b3f56a8d88 --- /dev/null +++ b/zh/api/Phalcon_Flash_Session.rst @@ -0,0 +1,135 @@ +Class **Phalcon\\Flash\\Session** +================================= + +*extends* :doc:`Phalcon\\Flash ` + +Temporarily stores the messages in session, then messages can be printed in the next request + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +protected *array* **_getSessionMessages** () + +Returns the messages stored in session + + + +protected **_setSessionMessages** () + +Stores the messages in session + + + +public **message** (*string* $type, *string* $message) + +Adds a message to the session flasher + + + +public *array* **getMessages** (*string* $type, *boolean* $remove) + +Returns the messages in the session flasher + + + +public **output** (*boolean* $remove) + +Prints the messages in the session flasher + + + +public **__construct** (*array* $cssClasses) inherited from Phalcon\\Flash + +Phalcon\\Flash constructor + + + +public **setImplicitFlush** (*unknown* $implicitFlush) inherited from Phalcon\\Flash + +Set the if the output must be implictly flushed to the output or returned as string + + + +public **setAutomaticHtml** (*boolean* $automaticHtml) inherited from Phalcon\\Flash + +Set the if the output must be implictly formatted with HTML + + + +public **setCssClasses** (*array* $cssClasses) inherited from Phalcon\\Flash + +Set an array with CSS classes to format the messages + + + +public *string* **error** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML error message + +.. code-block:: php + + error('This is an error'); + + + + +public *string* **notice** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML notice/information message + +.. code-block:: php + + notice('This is an information'); + + + + +public *string* **success** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML success message + +.. code-block:: php + + success('The process was finished successfully'); + + + + +public *string* **warning** (*string* $message) inherited from Phalcon\\Flash + +Shows a HTML warning message + +.. code-block:: php + + warning('Hey, this is important'); + + + + +public **outputMessage** (*string* $type, *string* $message) inherited from Phalcon\\Flash + +Outputs a message formatting it with HTML + + + diff --git a/zh/api/Phalcon_Http_Request.rst b/zh/api/Phalcon_Http_Request.rst new file mode 100755 index 000000000000..6b455f0b2793 --- /dev/null +++ b/zh/api/Phalcon_Http_Request.rst @@ -0,0 +1,294 @@ +Class **Phalcon\\Http\\Request** +================================ + +Encapsulates request information for easy and secure access from application controllers. The request object is a simple value object that is passed between the dispatcher and controller classes. It packages the HTTP request environment. + +.. code-block:: php + + isPost() == true) { + if ($request->isAjax() == true) { + echo 'Request was made using POST and AJAX'; + } + } + + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +public *mixed* **get** (*string* $name, *string|array* $filters) + +Gets a variable from the $_REQUEST superglobal applying filters if needed + +.. code-block:: php + + get("user_email"); + + //Returns value from $_REQUEST["user_email"] with sanitizing + $userEmail = $request->get("user_email", "email"); + + + + +public *mixed* **getPost** (*string* $name, *string|array* $filters) + +Gets a variable from the $_POST superglobal applying filters if needed + +.. code-block:: php + + getPost("user_email"); + + //Returns value from $_POST["user_email"] with sanitizing + $userEmail = $request->getPost("user_email", "email"); + + + + +public *mixed* **getQuery** (*string* $name, *string|array* $filters) + +Gets variable from $_GET superglobal applying filters if needed + +.. code-block:: php + + getQuery("id"); + + //Returns value from $_GET["id"] with sanitizing + $id = $request->getQuery("id", "int"); + + + + +public *mixed* **getServer** (*string* $name) + +Gets variable from $_SERVER superglobal + + + +public *boolean* **has** (*string* $name) + +Checks whether $_SERVER superglobal has certain index + + + +public *boolean* **hasPost** (*string* $name) + +Checks whether $_POST superglobal has certain index + + + +public *boolean* **hasQuery** (*string* $name) + +Checks whether $_SERVER superglobal has certain index + + + +public *mixed* **hasServer** (*string* $name) + +Checks whether $_SERVER superglobal has certain index + + + +public *string* **getHeader** (*string* $header) + +Gets HTTP header from request data + + + +public *string* **getScheme** () + +Gets HTTP schema (http/https) + + + +public *boolean* **isAjax** () + +Checks whether request has been made using ajax. Checks if $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest' + + + +public *boolean* **isSoapRequested** () + +Checks whether request has been made using SOAP + + + +public *boolean* **isSecureRequest** () + +Checks whether request has been made using any secure layer + + + +public *string* **getRawBody** () + +Gets HTTP raws request body + + + +public *string* **getServerAddress** () + +Gets active server address IP + + + +public *string* **getServerName** () + +Gets active server name + + + +public *string* **getHttpHost** () + +Gets information about schema, host and port used by the request + + + +public *string* **getClientAddress** (*boolean* $trustForwardedHeader) + +Gets most possibly client IPv4 Address. This methods search in $_SERVER['REMOTE_ADDR'] and optionally in $_SERVER['HTTP_X_FORWARDED_FOR'] + + + +public *string* **getMethod** () + +Gets HTTP method which request has been made + + + +public *string* **getUserAgent** () + +Gets HTTP user agent used to made the request + + + +public **isMethod** (*string|array* $methods) + +Check if HTTP method match any of the passed methods + + + +public *boolean* **isPost** () + +Checks whether HTTP method is POST. if $_SERVER['REQUEST_METHOD']=='POST' + + + +public *boolean* **isGet** () + +Checks whether HTTP method is GET. if $_SERVER['REQUEST_METHOD']=='GET' + + + +public *boolean* **isPut** () + +Checks whether HTTP method is PUT. if $_SERVER['REQUEST_METHOD']=='PUT' + + + +public *boolean* **isHead** () + +Checks whether HTTP method is HEAD. if $_SERVER['REQUEST_METHOD']=='HEAD' + + + +public *boolean* **isDelete** () + +Checks whether HTTP method is DELETE. if $_SERVER['REQUEST_METHOD']=='DELETE' + + + +public *boolean* **isOptions** () + +Checks whether HTTP method is OPTIONS. if $_SERVER['REQUEST_METHOD']=='OPTIONS' + + + +public *boolean* **hasFiles** () + +Checks whether request include attached files + + + +public :doc:`Phalcon\\Http\\Request\\File ` [] **getUploadedFiles** () + +Gets attached files as Phalcon\\Http\\Request\\File instances + + + +public *string* **getHTTPReferer** () + +Gets web page that refers active request. ie: http://www.google.com + + + +protected *array* **_getQualityHeader** () + +Process a request header and return an array of values with their qualities + + + +protected *string* **_getBestQuality** () + +Process a request header and return the one with best quality + + + +public *array* **getAcceptableContent** () + +Gets array with mime/types and their quality accepted by the browser/client from $_SERVER['HTTP_ACCEPT'] + + + +public *array* **getBestAccept** () + +Gets best mime/type accepted by the browser/client from $_SERVER['HTTP_ACCEPT'] + + + +public *array* **getClientCharsets** () + +Gets charsets array and their quality accepted by the browser/client from $_SERVER['HTTP_ACCEPT_CHARSET'] + + + +public *string* **getBestCharset** () + +Gets best charset accepted by the browser/client from $_SERVER['HTTP_ACCEPT_CHARSET'] + + + +public *array* **getLanguages** () + +Gets languages array and their quality accepted by the browser/client from $_SERVER['HTTP_ACCEPT_LANGUAGE'] + + + +public *string* **getBestLanguage** () + +Gets best language accepted by the browser/client from $_SERVER['HTTP_ACCEPT_LANGUAGE'] + + + diff --git a/zh/api/Phalcon_Http_Request_Exception.rst b/zh/api/Phalcon_Http_Request_Exception.rst new file mode 100755 index 000000000000..68757a9128a5 --- /dev/null +++ b/zh/api/Phalcon_Http_Request_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Http\\Request\\Exception** +=========================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Http\\Request will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Http_Request_File.rst b/zh/api/Phalcon_Http_Request_File.rst new file mode 100755 index 000000000000..bc9e1445fce4 --- /dev/null +++ b/zh/api/Phalcon_Http_Request_File.rst @@ -0,0 +1,60 @@ +Class **Phalcon\\Http\\Request\\File** +====================================== + +Provides OO wrappers to the $_FILES superglobal + +.. code-block:: php + + request->hasFiles() == true) { + //Print the real file names and their sizes + foreach ($this->request->getUploadedFiles() as $file){ + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } + } + + } + + + +Methods +--------- + +public **__construct** (*array* $file) + +Phalcon\\Http\\Request\\File constructor + + + +public *int* **getSize** () + +Returns the file size of the uploaded file + + + +public *string* **getName** () + +Returns the real name of the uploaded file + + + +public *string* **getTempName** () + +Returns the temporal name of the uploaded file + + + +public **moveTo** (*string* $destination) + +Move the temporary file to a destination + + + diff --git a/zh/api/Phalcon_Http_Response.rst b/zh/api/Phalcon_Http_Response.rst new file mode 100755 index 000000000000..6b5620588b15 --- /dev/null +++ b/zh/api/Phalcon_Http_Response.rst @@ -0,0 +1,160 @@ +Class **Phalcon\\Http\\Response** +================================= + +Part of the HTTP cycle is return responses to the clients. Phalcon\\HTTP\\Response is the Phalcon component responsible to achieve this task. HTTP responses are usually composed by headers and body. + +.. code-block:: php + + setStatusCode(200, "OK"); + $response->setContent("Hello"); + $response->send(); + + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +public :doc:`Phalcon\\Http\\Response ` **setStatusCode** (*int* $code, *string* $message) + +Sets the HTTP response code + +.. code-block:: php + + setStatusCode(404, "Not Found"); + + + + +public :doc:`Phalcon\\Http\\Response\\Headers ` **getHeaders** () + +Returns headers set by the user + + + +public :doc:`Phalcon\\Http\\Response ` **setHeader** (*string* $name, *string* $value) + +Overwrites a header in the response + +.. code-block:: php + + setHeader("Content-Type", "text/plain"); + + + + +public :doc:`Phalcon\\Http\\Response ` **setRawHeader** (*string* $header) + +Send a raw header to the response + +.. code-block:: php + + setRawHeader("HTTP/1.1 404 Not Found"); + + + + +public :doc:`Phalcon\\Http\\Response ` **resetHeaders** () + +Resets all the stablished headers + + + +public :doc:`Phalcon\\Http\\Response ` **setExpires** (*DateTime* $datetime) + +Sets output expire time header + + + +public :doc:`Phalcon\\Http\\Response ` **setNotModified** () + +Sends a Not-Modified response + + + +public **setContentType** (*string* $contentType, *string* $charset) + +Sets the response content-type mime, optionally the charset + +.. code-block:: php + + setContentType('application/pdf'); + $response->setContentType('text/plain', 'UTF-8'); + + + + +public :doc:`Phalcon\\Http\\Response ` **redirect** (*string* $location, *boolean* $externalRedirect, *int* $statusCode) + +Redirect by HTTP to another action or URL + +.. code-block:: php + + redirect("posts/index"); + $response->redirect("http://en.wikipedia.org", true); + $response->redirect("http://www.example.com/new-location", true, 301); + + + + +public :doc:`Phalcon\\Http\\Response ` **setContent** (*string* $content) + +Sets HTTP response body + +.. code-block:: php + + setContent("

Hello!

"); + + + + +public :doc:`Phalcon\\Http\\Response ` **appendContent** (*string* $content) + +Appends a string to the HTTP response body + + + +public *string* **getContent** () + +Gets HTTP response body + + + +public :doc:`Phalcon\\Http\\Response ` **sendHeaders** () + +Sends headers to the client + + + +public :doc:`Phalcon\\Http\\Response ` **send** () + +Prints out HTTP response to the client + + + diff --git a/zh/api/Phalcon_Http_Response_Exception.rst b/zh/api/Phalcon_Http_Response_Exception.rst new file mode 100755 index 000000000000..23c9b301086d --- /dev/null +++ b/zh/api/Phalcon_Http_Response_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Http\\Response\\Exception** +============================================ + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Http\\Response will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Http_Response_Headers.rst b/zh/api/Phalcon_Http_Response_Headers.rst new file mode 100755 index 000000000000..5abe96a8c9f2 --- /dev/null +++ b/zh/api/Phalcon_Http_Response_Headers.rst @@ -0,0 +1,50 @@ +Class **Phalcon\\Http\\Response\\Headers** +========================================== + +This class is a bag to manage the response headers + + +Methods +--------- + +public **__construct** () + +... + + +public **set** (*string* $name, *string* $value) + +Sets a header to be sent at the end of the request + + + +public *string* **get** (*string* $name) + +Gets a header value from the internal bag + + + +public **setRaw** (*string* $header) + +Sets a raw header to be sent at the end of the request + + + +public *boolean* **send** () + +Sends the headers to the client + + + +public **reset** () + +Reset set headers + + + +public static :doc:`Phalcon\\Http\\Response\\Headers ` **__set_state** (*unknown* $data) + +Restore a Phalcon\\Http\\Response\\Headers object + + + diff --git a/zh/api/Phalcon_Loader.rst b/zh/api/Phalcon_Loader.rst new file mode 100755 index 000000000000..8ab4602b19ec --- /dev/null +++ b/zh/api/Phalcon_Loader.rst @@ -0,0 +1,107 @@ +Class **Phalcon\\Loader** +========================= + +This component helps to load your project classes automatically based on some conventions + +.. code-block:: php + + registerNamespaces(array( + 'Example\\Base' => 'vendor/example/base/', + 'Example\\Adapter' => 'vendor/example/adapter/', + 'Example' => 'vendor/example/' + )); + + //register autoloader + $loader->register(); + + //Requiring class will automatically include file vendor/example/adapter/Some.php + $adapter = Example\Adapter\Some(); + + + +Methods +--------- + +public **__construct** () + +... + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public :doc:`Phalcon\\Loader ` **setExtensions** (*array* $extensions) + +Sets an array of extensions that the Loader must check together with the path + + + +public :doc:`Phalcon\\Loader ` **registerNamespaces** (*array* $namespaces) + +Register namespaces and their related directories + + + +public :doc:`Phalcon\\Loader ` **registerPrefixes** (*unknown* $prefixes) + +Register directories on which "not found" classes could be found + + + +public :doc:`Phalcon\\Loader ` **registerDirs** (*array* $directories) + +Register directories on which "not found" classes could be found + + + +public :doc:`Phalcon\\Loader ` **registerClasses** (*unknown* $classes) + +Register classes and their locations + + + +public :doc:`Phalcon\\Loader ` **register** () + +Register the autoload method + + + +public **unregister** () + +Unregister the autoload method + + + +public *boolean* **autoLoad** (*string* $className) + +Makes the work of autoload registered classes + + + +public *string* **getFoundPath** () + +Get the path when a class was found + + + +public *string* **getCheckedPath** () + +Get the path the loader is checking for a path + + + diff --git a/zh/api/Phalcon_Loader_Exception.rst b/zh/api/Phalcon_Loader_Exception.rst new file mode 100755 index 000000000000..3206df522934 --- /dev/null +++ b/zh/api/Phalcon_Loader_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Loader\\Exception** +==================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Loader will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Logger.rst b/zh/api/Phalcon_Logger.rst new file mode 100755 index 000000000000..954e90a156ca --- /dev/null +++ b/zh/api/Phalcon_Logger.rst @@ -0,0 +1,84 @@ +Class **Phalcon\\Logger** +========================= + +Phalcon\\Logger is a component whose purpose is to create logs using different backends via adapters, generating options, formats and filters also implementing transactions. + +.. code-block:: php + + log("This is a message"); + $logger->log("This is an error", Phalcon\Logger::ERROR); + $logger->error("This is another error"); + $logger->close(); + + + +Constants +--------- + +*integer* **SPECIAL** + +*integer* **CUSTOM** + +*integer* **DEBUG** + +*integer* **INFO** + +*integer* **NOTICE** + +*integer* **WARNING** + +*integer* **ERROR** + +*integer* **ALERT** + +*integer* **CRITICAL** + +*integer* **EMERGENCE** + +Methods +--------- + +public **debug** (*string* $message) + +Sends/Writes a debug message to the log + + + +public **error** (*string* $message) + +Sends/Writes an error message to the log + + + +public **info** (*string* $message) + +Sends/Writes an info message to the log + + + +public **notice** (*string* $message) + +Sends/Writes a notice message to the log + + + +public **warning** (*string* $message) + +Sends/Writes a warning message to the log + + + +public **alert** (*string* $message) + +Sends/Writes an alert message to the log + + + +public **log** (*unknown* $message, *unknown* $type) + +... + + diff --git a/zh/api/Phalcon_Logger_Adapter_File.rst b/zh/api/Phalcon_Logger_Adapter_File.rst new file mode 100755 index 000000000000..c1c6a4d28483 --- /dev/null +++ b/zh/api/Phalcon_Logger_Adapter_File.rst @@ -0,0 +1,159 @@ +Class **Phalcon\\Logger\\Adapter\\File** +======================================== + +*extends* :doc:`Phalcon\\Logger ` + +Adapter to store logs in plain text files + +.. code-block:: php + + log("This is a message"); + $logger->log("This is an error", Phalcon\Logger::ERROR); + $logger->error("This is another error"); + $logger->close(); + + + +Constants +--------- + +*integer* **SPECIAL** + +*integer* **CUSTOM** + +*integer* **DEBUG** + +*integer* **INFO** + +*integer* **NOTICE** + +*integer* **WARNING** + +*integer* **ERROR** + +*integer* **ALERT** + +*integer* **CRITICAL** + +*integer* **EMERGENCE** + +Methods +--------- + +public **__construct** (*string* $name, *array* $options) + +Phalcon\\Logger\\Adapter\\File constructor + + + +public **setFormat** (*string* $format) + +Set the log format + + + +public *format* **getFormat** () + +Returns the log format + + + +public *string* **getTypeString** (*integer* $type) + +Returns the string meaning of a logger constant + + + +protected *string* **_applyFormat** () + +Applies the internal format to the message + + + +public **setDateFormat** (*string* $date) + +Sets the internal date format + + + +public *string* **getDateFormat** () + +Returns the internal date format + + + +public **log** (*string* $message, *int* $type) + +Sends/Writes messages to the file log + + + +public **begin** () + +Starts a transaction + + + +public **commit** () + +Commits the internal transaction + + + +public **rollback** () + +Rollbacks the internal transaction + + + +public *boolean* **close** () + +Closes the logger + + + +public **__wakeup** () + +Opens the internal file handler after unserialization + + + +public **debug** (*string* $message) inherited from Phalcon\\Logger + +Sends/Writes a debug message to the log + + + +public **error** (*string* $message) inherited from Phalcon\\Logger + +Sends/Writes an error message to the log + + + +public **info** (*string* $message) inherited from Phalcon\\Logger + +Sends/Writes an info message to the log + + + +public **notice** (*string* $message) inherited from Phalcon\\Logger + +Sends/Writes a notice message to the log + + + +public **warning** (*string* $message) inherited from Phalcon\\Logger + +Sends/Writes a warning message to the log + + + +public **alert** (*string* $message) inherited from Phalcon\\Logger + +Sends/Writes an alert message to the log + + + diff --git a/zh/api/Phalcon_Logger_Exception.rst b/zh/api/Phalcon_Logger_Exception.rst new file mode 100755 index 000000000000..20aaabc6ecbc --- /dev/null +++ b/zh/api/Phalcon_Logger_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Logger\\Exception** +==================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Logger will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Logger_Item.rst b/zh/api/Phalcon_Logger_Item.rst new file mode 100755 index 000000000000..163a2760fb04 --- /dev/null +++ b/zh/api/Phalcon_Logger_Item.rst @@ -0,0 +1,33 @@ +Class **Phalcon\\Logger\\Item** +=============================== + +Represents each item in a logger transaction + + +Methods +--------- + +public **__construct** (*string* $message, *integer* $type, *integer* $time) + +Phalcon\\Logger\\Item contructor + + + +public *string* **getMessage** () + +Returns the message + + + +public *integer* **getType** () + +Returns the log type + + + +public *integer* **getTime** () + +Returns log timestamp + + + diff --git a/zh/api/Phalcon_Mvc_Application.rst b/zh/api/Phalcon_Mvc_Application.rst new file mode 100644 index 000000000000..cdffd2c6addb --- /dev/null +++ b/zh/api/Phalcon_Mvc_Application.rst @@ -0,0 +1,112 @@ +Class **Phalcon\\Mvc\\Application** +=================================== + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +This component encapsulates all the complex operations behind instantiating every component needed and integrating it with the rest to allow the MVC pattern to operate as desired. + +.. code-block:: php + + registerModules(array( + 'frontend' => array( + 'className' => 'Multiple\Frontend\Module', + 'path' => '../apps/frontend/Module.php' + ), + 'backend' => array( + 'className' => 'Multiple\Backend\Module', + 'path' => '../apps/backend/Module.php' + ) + )); + } + } + + $application = new Application(); + $application->main(); + + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the DependencyInjector container + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public **registerModules** (*array* $modules) + +Register an array of modules present in the application + +.. code-block:: php + + registerModules(array( + 'frontend' => array( + 'className' => 'Multiple\Frontend\Module', + 'path' => '../apps/frontend/Module.php' + ), + 'backend' => array( + 'className' => 'Multiple\Backend\Module', + 'path' => '../apps/backend/Module.php' + ) + )); + + + + +public *array* **getModules** () + +Return the modules registered in the application + + + +public :doc:`Phalcon\\Http\\Response ` **handle** () + +Handles a MVC request + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_Application_Exception.rst b/zh/api/Phalcon_Mvc_Application_Exception.rst new file mode 100644 index 000000000000..d627fdb88e20 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Application_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Application\\Exception** +============================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Application class will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Collection.rst b/zh/api/Phalcon_Mvc_Collection.rst new file mode 100644 index 000000000000..72bef59641e3 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Collection.rst @@ -0,0 +1,314 @@ +Class **Phalcon\\Mvc\\Collection** +================================== + +This component implements a high level abstraction for NoSQL databases which works with documents + + +Constants +--------- + +*integer* **OP_NONE** + +*integer* **OP_CREATE** + +*integer* **OP_UPDATE** + +*integer* **OP_DELETE** + +Methods +--------- + +public **__construct** (:doc:`Phalcon\\DI ` $dependencyInjector) + + + + + +public **setId** (*mixed* $id) + +Sets a value for the _id propery, creates a MongoId object if needed + + + +public *MongoId* **getId** () + +Returns the value of the _id property + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injection container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the dependency injection container + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public *array* **getReservedAttributes** () + +Returns an array with reserved properties that cannot be part of the insert/update + + + +protected :doc:`Phalcon\\Mvc\\Collection ` **setSource** () + +Sets collection name which model should be mapped + + + +public *string* **getSource** () + +Returns collection name mapped in the model + + + +public **setConnectionService** (*string* $connectionService) + +Sets a service in the services container that returns the Mongo database + + + +public *MongoDb* **getConnection** () + +Retrieves a database connection + + + +public *mixed* **readAttribute** (*string* $attribute) + +Reads an attribute value by its name echo $robot->readAttribute('name'); + + + +public **writeAttribute** (*string* $attribute, *mixed* $value) + +Writes an attribute value by its name $robot->writeAttribute('name', 'Rosey'); + + + +protected static :doc:`Phalcon\\Mvc\\Collection ` **dumpResult** () + +Returns a cloned collection + + + +protected static *array* **_getResultset** () + +Returns a collection resultset + + + +protected *boolean* **_preSave** () + +Executes internal hooks before save a document + + + +protected *boolean* **_postSave** () + +Executes internal events after save a document + + + +protected **validate** () + +Executes validators on every validation call + +.. code-block:: php + + validate(new ExclusionIn(array( + 'field' => 'status', + 'domain' => array('A', 'I') + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + + +public *boolean* **validationHasFailed** () + +Check whether validation process has generated any messages + +.. code-block:: php + + validate(new ExclusionIn(array( + 'field' => 'status', + 'domain' => array('A', 'I') + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + + +protected *boolean* **_callEvent** () + +Fires an internal event + + + +protected *boolean* **_callEventCancel** () + +Fires an internal event that cancels the operation + + + +protected *boolean* **_cancelOperation** () + +Cancel the current operation + + + +protected **_exists** () + +Checks if the document exists in the collection + + + +public **save** () + + + + + +public static :doc:`Phalcon\\Mvc\\Collection ` **findById** (*string* $id) + +Find a document by its id + + + +public static *array* **findFirst** (*array* $parameters) + +Allows to query the first record that match the specified conditions + +.. code-block:: php + + name; + + //What's the first mechanical robot in robots table? + $robot = Robots::findFirst(array( + array("type" => "mechanical") + )); + echo "The first mechanical robot name is ", $robot->name; + + //Get first virtual robot ordered by name + $robot = Robots::findFirst(array( + array("type" => "mechanical"), + "order" => array("name" => 1) + )); + echo "The first virtual robot name is ", $robot->name; + + + + +public static *array* **find** (*array* $parameters) + +Allows to query a set of records that match the specified conditions + +.. code-block:: php + + "mechanical") + )); + echo "There are ", count($robots); + + //Get and print virtual robots ordered by name + $robots = Robots::findFirst(array( + array("type" => "virtual"), + "order" => array("name" => 1) + )); + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + //Get first 100 virtual robots ordered by name + $robots = Robots::find(array( + array("type" => "virtual"), + "order" => array("name" => 1), + "limit" => 100 + )); + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + + + +public static **count** (*unknown* $parameters) + + + + + +public *boolean* **delete** () + +Deletes a model instance. Returning true on success or false otherwise. + +.. code-block:: php + + delete(); + + foreach(Robots::find() as $robot){ + $robot->delete(); + } + + + + diff --git a/zh/api/Phalcon_Mvc_Collection_Exception.rst b/zh/api/Phalcon_Mvc_Collection_Exception.rst new file mode 100644 index 000000000000..16c1f734565e --- /dev/null +++ b/zh/api/Phalcon_Mvc_Collection_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Collection\\Exception** +============================================= + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Collection\\* classes will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Collection_Manager.rst b/zh/api/Phalcon_Mvc_Collection_Manager.rst new file mode 100644 index 000000000000..6f3ea65cdc79 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Collection_Manager.rst @@ -0,0 +1,21 @@ +Class **Phalcon\\Mvc\\Collection\\Manager** +=========================================== + +Methods +--------- + +public **__construct** () + +... + + +public **isInitialized** (*unknown* $collection) + +... + + +public **initialize** () + +... + + diff --git a/zh/api/Phalcon_Mvc_Controller.rst b/zh/api/Phalcon_Mvc_Controller.rst new file mode 100755 index 000000000000..c060107e3d85 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Controller.rst @@ -0,0 +1,80 @@ +Class **Phalcon\\Mvc\\Controller** +================================== + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +Every application controller should extend this class that encapsulates all the controller functionality The controllers provide the “flow” between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation. + +.. code-block:: php + + dispatcher->forward(array('controller' => 'people', 'action' => 'index')); + } + + //This action will be executed when a non existent action is requested + public function notFoundAction() + { + + } + + } + + + +Methods +--------- + +final public **__construct** () + +Phalcon\\Mvc\\Controller constructor + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_Dispatcher.rst b/zh/api/Phalcon_Mvc_Dispatcher.rst new file mode 100644 index 000000000000..1df2aea8c499 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Dispatcher.rst @@ -0,0 +1,190 @@ +Class **Phalcon\\Mvc\\Dispatcher** +================================== + +*extends* :doc:`Phalcon\\Dispatcher ` + +Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller. + +.. code-block:: php + + setDI($di); + + $dispatcher->setControllerName('posts'); + $dispatcher->setActionName('index'); + $dispatcher->setParams(array()); + + $controller = $dispatcher->dispatch(); + + + +Constants +--------- + +*integer* **EXCEPTION_NO_DI** + +*integer* **EXCEPTION_CYCLIC_ROUTING** + +*integer* **EXCEPTION_HANDLER_NOT_FOUND** + +*integer* **EXCEPTION_INVALID_PARAMS** + +*integer* **EXCEPTION_ACTION_NOT_FOUND** + +Methods +--------- + +public **setControllerSuffix** (*string* $controllerSuffix) + +Sets the default controller suffix + + + +public **setDefaultController** (*string* $controllerName) + +Sets the default controller name + + + +public **setControllerName** (*string* $controllerName) + +Sets the controller name to be dispatched + + + +public *string* **getControllerName** () + +Gets last dispatched controller name + + + +protected **_throwDispatchException** () + +Throws an internal exception + + + +public :doc:`Phalcon\\Mvc\\Controller ` **getLastController** () + +Returns the lastest dispatched controller + + + +public :doc:`Phalcon\\Mvc\\Controller ` **getActiveController** () + +Returns the active controller in the dispatcher + + + +public **__construct** () inherited from Phalcon\\Dispatcher + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\Dispatcher + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\Dispatcher + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\Dispatcher + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\Dispatcher + +Returns the internal event manager + + + +public **setActionSuffix** (*string* $actionSuffix) inherited from Phalcon\\Dispatcher + +Sets the default action suffix + + + +public **setDefaultNamespace** (*string* $namespace) inherited from Phalcon\\Dispatcher + +Sets the default namespace + + + +public **setDefaultAction** (*string* $actionName) inherited from Phalcon\\Dispatcher + +Sets the default action name + + + +public **setActionName** (*string* $actionName) inherited from Phalcon\\Dispatcher + +Sets the action name to be dispatched + + + +public *string* **getActionName** () inherited from Phalcon\\Dispatcher + +Gets last dispatched action name + + + +public **setParams** (*array* $params) inherited from Phalcon\\Dispatcher + +Sets action params to be dispatched + + + +public *array* **getParams** () inherited from Phalcon\\Dispatcher + +Gets action params + + + +public **setParam** (*mixed* $param, *mixed* $value) inherited from Phalcon\\Dispatcher + +Set a param by its name or numeric index + + + +public *mixed* **getParam** (*mixed* $param, *string|array* $filters) inherited from Phalcon\\Dispatcher + +Gets a param by its name or numeric index + + + +public *boolean* **isFinished** () inherited from Phalcon\\Dispatcher + +Checks if the dispatch loop is finished or have more pendent controllers/tasks to disptach + + + +public *mixed* **getReturnedValue** () inherited from Phalcon\\Dispatcher + +Returns value returned by the lastest dispatched action + + + +public *object* **dispatch** () inherited from Phalcon\\Dispatcher + +Dispatches a handle action taking into account the routing parameters + + + +public **forward** (*array* $forward) inherited from Phalcon\\Dispatcher + +Forwards the execution flow to another controller/action + + + diff --git a/zh/api/Phalcon_Mvc_Dispatcher_Exception.rst b/zh/api/Phalcon_Mvc_Dispatcher_Exception.rst new file mode 100644 index 000000000000..517e8dcea159 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Dispatcher_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Dispatcher\\Exception** +============================================= + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Dispatcher will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Micro.rst b/zh/api/Phalcon_Mvc_Micro.rst new file mode 100644 index 000000000000..011095d80573 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Micro.rst @@ -0,0 +1,149 @@ +Class **Phalcon\\Mvc\\Micro** +============================= + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +With Phalcon you can create "Micro-Framework like" applications. By doing this, you only need to write a minimal amount of code to create a PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way. + +.. code-block:: php + + get('/say/welcome/{name}', function ($name) { + echo "

Welcome $name!

"; + }); + + $app->handle(); + + + +Methods +--------- + +public **__construct** () + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the DependencyInjector container + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the events manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public **map** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler without any HTTP method constraint + + + +public **get** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler that only matches if the HTTP method is GET + + + +public **post** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler that only matches if the HTTP method is POST + + + +public **put** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler that only matches if the HTTP method is PUT + + + +public **head** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler that only matches if the HTTP method is HEAD + + + +public **delete** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler that only matches if the HTTP method is DELETE + + + +public **options** (*string* $routePattern, *callable* $handler) + +Maps a route to a handler that only matches if the HTTP method is GET + + + +public **notFound** (*callable* $handler) + +Sets a handler that will be called when the router doesn't match any of the defined routes + + + +public :doc:`Phalcon\\Mvc\\Router ` **getRouter** () + +Returns the internal router used by the application + + + +public *object* **getService** (*unknown* $serviceName) + +Obtains a service from the DI + + + +public **getSharedService** (*unknown* $serviceName) + +Obtains a shared service from the DI + + + +public *mixed* **handle** () + +Handle the whole request + + + +public **setActiveHandler** (*callable* $activeHandler) + +Sets externally the handler that must be called by the matched route + + + +public *callable* **getActiveHandler** () + +Return the handler that will be called for the matched route + + + +public **getReturnedValue** () + +Returns the value returned by the executed handler + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_Micro_Exception.rst b/zh/api/Phalcon_Mvc_Micro_Exception.rst new file mode 100644 index 000000000000..1a0a83826901 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Micro_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Micro\\Exception** +======================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Micro will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Model.rst b/zh/api/Phalcon_Mvc_Model.rst new file mode 100755 index 000000000000..8d60fa9994dc --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model.rst @@ -0,0 +1,783 @@ +Class **Phalcon\\Mvc\\Model** +============================= + +*implements* Serializable + +Phalcon\\Mvc\\Model connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It‘s an implementation of the object-relational mapping (ORM). A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models. Phalcon\\Mvc\\Model is the first ORM written in C-language for PHP, giving to developers high performance when interacting with databases while is also easy to use. + +.. code-block:: php + + type = 'mechanical' + $robot->name = 'Astro Boy'; + $robot->year = 1952; + if ($robot->save() == false) { + echo "Umh, We can store robots: "; + foreach ($robot->getMessages() as $message) { + echo $message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } + + + +Constants +--------- + +*integer* **OP_NONE** + +*integer* **OP_CREATE** + +*integer* **OP_UPDATE** + +*integer* **OP_DELETE** + +Methods +--------- + +final public **__construct** (:doc:`Phalcon\\DI ` $dependencyInjector, *string* $managerService, *string* $dbService) + +Phalcon\\Mvc\\Model constructor + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injection container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the dependency injection container + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +protected static *array* **_createSQLSelect** () + +Creates a SQL statement which returns many rows + + + +protected static **_getOrCreateResultset** () + +Gets a resulset from the cache or creates one + + + +public :doc:`Phalcon\\Mvc\\Model ` **setTransaction** (:doc:`Phalcon\\Mvc\\Model\\Transaction ` $transaction) + +Sets a transaction related to the Model instance + +.. code-block:: php + + get(); + + $robot = new Robots(); + $robot->setTransaction($transaction); + $robot->name = 'WALL·E'; + $robot->created_at = date('Y-m-d'); + if($robot->save()==false){ + $transaction->rollback("Can't save robot"); + } + + $robotPart = new RobotParts(); + $robotPart->setTransaction($transaction); + $robotPart->type = 'head'; + if ($robotPart->save() == false) { + $transaction->rollback("Can't save robot part"); + } + + $transaction->commit(); + + } + catch(Phalcon\Mvc\Model\Transaction\Failed $e){ + echo 'Failed, reason: ', $e->getMessage(); + } + + + + +protected :doc:`Phalcon\\Mvc\\Model ` **setSource** () + +Sets table name which model should be mapped + + + +public *string* **getSource** () + +Returns table name mapped in the model + + + +protected :doc:`Phalcon\\Mvc\\Model ` **setSchema** () + +Sets schema name where table mapped is located + + + +public *string* **getSchema** () + +Returns schema name where table mapped is located + + + +public **setConnectionService** (*string* $connectionService) + +Sets DependencyInjection connection service + + + +public *$connectionService* **getConnectionService** () + +Returns DependencyInjection connection service + + + +public **setForceExists** (*boolean* $forceExists) + +Forces that model doesn't need to be checked if exists before store it + + + +public :doc:`Phalcon\\Db ` **getConnection** () + +Gets internal database connection + + + +public static :doc:`Phalcon\\Mvc\\Model ` $result **dumpResult** (:doc:`Phalcon\\Mvc\\Model ` $base, *array* $result) + +Assigns values to a model from an array returning a new model + +.. code-block:: php + + 'mechanical', + 'name' => 'Astro Boy', + 'year' => 1952 + )); + + + + +public static :doc:`Phalcon\\Mvc\\Model\\Resultset ` **find** (*array* $parameters) + +Allows to query a set of records that match the specified conditions + +.. code-block:: php + + "name")); + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + //Get first 100 virtual robots ordered by name + $robots = Robots::find(array("type='virtual'", "order" => "name", "limit" => 100)); + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + + + +public static :doc:`Phalcon\\Mvc\\Model ` **findFirst** (*array* $parameters) + +Allows to query the first record that match the specified conditions + +.. code-block:: php + + name; + + //What's the first mechanical robot in robots table? + $robot = Robots::findFirst("type='mechanical'"); + echo "The first mechanical robot name is ", $robot->name; + + //Get first virtual robot ordered by name + $robot = Robots::findFirst(array("type='virtual'", "order" => "name")); + echo "The first virtual robot name is ", $robot->name; + + + + +public static :doc:`Phalcon\\Mvc\\Model\\Criteria ` **query** (*unknown* $dependencyInjector) + +Create a criteria for a especific model + + + +protected *boolean* **_exists** () + +Checks if the current record already exists or not + + + +protected static :doc:`Phalcon\\Mvc\\Model\\Resultset ` **_prepareGroupResult** () + +Generate a SQL SELECT statement for an aggregate + + + +protected static *array|Phalcon\Mvc\Model\Resultset* **_getGroupResult** () + +Generate a resulset from an SQL select with aggregations + + + +public static *int* **count** (*array* $parameters) + +Allows to count how many records match the specified conditions + +.. code-block:: php + + 'price')); + echo "The total price of robots is ", $sum; + + //How much are mechanical robots? + $sum = Robots::sum(array("type='mechanical'", 'column' => 'price')); + echo "The total price of mechanical robots is ", $sum; + + + + +public static *mixed* **maximum** (*array* $parameters) + +Allows to get the maximum value of a column that match the specified conditions + +.. code-block:: php + + 'id')); + echo "The maximum robot id is: ", $id; + + //What is the maximum id of mechanical robots? + $sum = Robots::maximum(array("type='mechanical'", 'column' => 'id')); + echo "The maximum robot id of mechanical robots is ", $id; + + + + +public static *mixed* **minimum** (*array* $parameters) + +Allows to get the minimum value of a column that match the specified conditions + +.. code-block:: php + + 'id')); + echo "The minimum robot id is: ", $id; + + //What is the minimum id of mechanical robots? + $sum = Robots::minimum(array("type='mechanical'", 'column' => 'id')); + echo "The minimum robot id of mechanical robots is ", $id; + + + + +public static *double* **average** (*array* $parameters) + +Allows to calculate the average value on a column matching the specified conditions + +.. code-block:: php + + 'price')); + echo "The average price is ", $average; + + //What's the average price of mechanical robots? + $average = Robots::average(array("type='mechanical'", 'column' => 'price')); + echo "The average price of mechanical robots is ", $average; + + + + +protected *boolean* **_callEvent** () + +Fires an internal event + + + +protected *boolean* **_callEventCancel** () + +Fires an internal event that cancels the operation + + + +protected *boolean* **_cancelOperation** () + +Cancel the current operation + + + +public **appendMessage** (:doc:`Phalcon\\Mvc\\Model\\Message ` $message) + +Appends a customized message on the validation process + +.. code-block:: php + + name == 'Peter') { + $message = new Message("Sorry, but a robot cannot be named Peter"); + $this->appendMessage($message); + } + } + } + + + + +protected **validate** () + +Executes validators on every validation call + +.. code-block:: php + + validate(new ExclusionIn(array( + 'field' => 'status', + 'domain' => array('A', 'I') + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + + +public *boolean* **validationHasFailed** () + +Check whether validation process has generated any messages + +.. code-block:: php + + validate(new ExclusionIn(array( + 'field' => 'status', + 'domain' => array('A', 'I') + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + + +public :doc:`Phalcon\\Mvc\\Model\\Message ` [] **getMessages** () + +Returns all the validation messages + +.. code-block:: php + + type = 'mechanical'; + $robot->name = 'Astro Boy'; + $robot->year = 1952; + if ($robot->save() == false) { + echo "Umh, We can't store robots right now "; + foreach ($robot->getMessages() as $message) { + echo $message; + } + } else { + echo "Great, a new robot was saved successfully!"; + } + + + + +protected *boolean* **_checkForeignKeys** () + +Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records + + + +protected *boolean* **_checkForeignKeysReverse** () + +Reads both "hasMany" and "hasOne" relations and check the virtual foreign keys when deleting records + + + +protected *boolean* **_preSave** () + +Executes internal hooks before save a record + + + +protected *boolean* **_postSave** () + +Executes internal events after save a record + + + +protected *boolean* **_doLowInsert** () + +Sends a pre-build INSERT SQL statement to the relational database system + + + +protected *boolean* **_doLowUpdate** () + +Sends a pre-build UPDATE SQL statement to the relational database system + + + +public *boolean* **save** () + +Inserts or updates a model instance. Returning true on success or false otherwise. + +.. code-block:: php + + type = 'mechanical' + $robot->name = 'Astro Boy'; + $robot->year = 1952; + $robot->save(); + + //Updating a robot name + $robot = Robots::findFirst("id=100"); + $robot->name = "Biomass"; + $robot->save(); + + + + +public *boolean* **create** () + +Inserts a model instance. If the instance already exists in the persistance it will throw an exception Returning true on success or false otherwise. + +.. code-block:: php + + type = 'mechanical' + $robot->name = 'Astro Boy'; + $robot->year = 1952; + $robot->create(); + + + + +public *boolean* **update** () + +Updates a model instance. If the instance doesn't exists in the persistance it will throw an exception Returning true on success or false otherwise. + +.. code-block:: php + + name = "Biomass"; + $robot->save(); + + + + +public *boolean* **delete** () + +Deletes a model instance. Returning true on success or false otherwise. + +.. code-block:: php + + delete(); + + foreach(Robots::find("type = 'mechanical'") as $robot){ + $robot->delete(); + } + + + + +public *int* **getOperationMade** () + +Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants + + + +public *mixed* **readAttribute** (*string* $attribute) + +Reads an attribute value by its name + +.. code-block:: php + + readAttribute('name'); + + + + +public **writeAttribute** (*string* $attribute, *mixed* $value) + +Writes an attribute value by its name + +.. code-block:: php + + writeAttribute('name', 'Rosey'); + + + + +protected **skipAttributes** () + +Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement + +.. code-block:: php + + skipAttributes(array('price')); + } + + } + + + + +protected **skipAttributesOnCreate** () + +Sets a list of attributes that must be skipped from the generated INSERT statement + +.. code-block:: php + + skipAttributesOnUpdate(array('created_at')); + } + + } + + + + +protected **skipAttributesOnUpdate** () + +Sets a list of attributes that must be skipped from the generated UPDATE statement + +.. code-block:: php + + skipAttributesOnUpdate(array('modified_in')); + } + + } + + + + +protected **hasOne** () + +Setup a 1-1 relation between two models + +.. code-block:: php + + hasOne('id', 'RobotsDescription', 'robots_id'); + } + + } + + + + +protected **belongsTo** () + +Setup a relation reverse 1-1 between two models + +.. code-block:: php + + belongsTo('robots_id', 'Robots', 'id'); + } + + } + + + + +protected **hasMany** () + +Setup a relation 1-n between two models + +.. code-block:: php + + hasMany('id', 'RobotsParts', 'robots_id'); + } + + } + + + + +protected :doc:`Phalcon\\Mvc\\Model\\Resultset\\Simple ` **getRelated** () + +Returns related records based on defined relations + + + +protected *mixed* **__getRelatedRecords** () + +Returns related records defined relations depending on the method name + + + +public *mixed* **__call** (*string* $method, *array* $arguments) + +Handles methods when a method does not exist + + + +public *string* **serialize** () + +Serializes the object ignoring connections or static properties + + + +public **unserialize** (*string* $data) + +Unserializes the object from a serialized string + + + diff --git a/zh/api/Phalcon_Mvc_Model_Criteria.rst b/zh/api/Phalcon_Mvc_Model_Criteria.rst new file mode 100644 index 000000000000..2248ee619c1e --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Criteria.rst @@ -0,0 +1,122 @@ +Class **Phalcon\\Mvc\\Model\\Criteria** +======================================= + +This class allows to build the array parameter required by Phalcon\\Mvc\\Model::find and Phalcon\\Mvc\\Model::findFirst, using an object-oriented interfase + + +Methods +--------- + +public **__construct** () + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the DependencyInjector container + + + +public **setModelName** (*string* $modelName) + +Set a model on which the query will be executed + + + +public *string* **getModelName** () + +Returns an internal model name on which the criteria will be applied + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **bind** (*string* $bindParams) + +Adds the bind parameter to the criteria + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **where** (*string* $conditions) + +Adds the conditions parameter to the criteria + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **conditions** (*string* $conditions) + +Adds the conditions parameter to the criteria + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **order** (*string* $orderColumns) + +Adds the order-by parameter to the criteria + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **limit** (*int* $limit, *int* $offset) + +Adds the limit parameter to the criteria + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **forUpdate** (*boolean* $forUpdate) + +Adds the "for_update" parameter to the criteria + + + +public :doc:`Phalcon\\Mvc\\Model\\Criteria ` **sharedLock** (*boolean* $sharedLock) + +Adds the "shared_lock" parameter to the criteria + + + +public *string* **getWhere** () + +Returns the conditions parameter in the criteria + + + +public *string* **getConditions** () + +Returns the conditions parameter in the criteria + + + +public *string* **getLimit** () + +Returns the limit parameter in the criteria + + + +public *string* **getOrder** () + +Returns the order parameter in the criteria + + + +public *string* **getParams** () + +Returns all the parameters defined in the criteria + + + +public static **fromInput** (:doc:`Phalcon\\DI ` $dependencyInjector, *string* $modelName, *array* $data) + +Builds a Phalcon\\Mvc\\Model\\Criteria based on an input array like $_POST + + + +public :doc:`Phalcon\\Mvc\\Model\\Resultset ` **execute** () + +Executes a find using the parameters built with the criteria + + + diff --git a/zh/api/Phalcon_Mvc_Model_Exception.rst b/zh/api/Phalcon_Mvc_Model_Exception.rst new file mode 100755 index 000000000000..6a0129c36301 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Model\\Exception** +======================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Model\\* classes will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Model_Manager.rst b/zh/api/Phalcon_Mvc_Model_Manager.rst new file mode 100755 index 000000000000..c4138b1a8fef --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Manager.rst @@ -0,0 +1,177 @@ +Class **Phalcon\\Mvc\\Model\\Manager** +====================================== + +This components controls the initialization of models, keeping record of relations between the different models of the application. A ModelsManager is injected to a model via a Dependency Injector Container such as Phalcon\\DI. + +.. code-block:: php + + set('modelsManager', function(){ + return new Phalcon\Mvc\Model\Manager(); + }); + + $robot = new Robots($dependencyInjector); + + + +Methods +--------- + +public **__construct** () + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the DependencyInjector container + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () + +Returns the internal event manager + + + +public **initialize** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Initializes a model in the model manager + + + +public *bool* **isInitialized** (*string* $modelName) + +Check of a model is already initialized + + + +public :doc:`Phalcon\\Mvc\\Model ` **getLastInitialized** () + +Get last initialized model + + + +public :doc:`Phalcon\\Mvc\\Model ` **load** (*unknown* $modelName) + +Loads a model throwing an exception if it doesn't exist + + + +public **addHasOne** (:doc:`Phalcon\\Mvc\\Model ` $model, *mixed* $fields, *string* $referenceModel, *mixed* $referencedFields, *array* $options) + +Setup a 1-1 relation between two models + + + +public **addBelongsTo** (:doc:`Phalcon\\Mvc\\Model ` $model, *mixed* $fields, *string* $referenceModel, *mixed* $referencedFields, *array* $options) + +Setup a relation reverse 1-1 between two models + + + +public **addHasMany** (:doc:`Phalcon\\Mvc\\Model ` $model, *mixed* $fields, *string* $referenceModel, *mixed* $referencedFields, *array* $options) + +Setup a relation 1-n between two models + + + +public *boolean* **existsBelongsTo** (*string* $modelName, *string* $modelRelation) + +Checks whether a model has a belongsTo relation with another model + + + +public *boolean* **existsHasMany** (*string* $modelName, *string* $modelRelation) + +Checks whether a model has a hasMany relation with another model + + + +public *boolean* **existsHasOne** (*string* $modelName, *string* $modelRelation) + +Checks whether a model has a hasOne relation with another model + + + +protected :doc:`Phalcon\\Mvc\\Model\\Resultset\\Simple ` **_getRelationRecords** () + +Helper method to query records based on a relation definition + + + +public :doc:`Phalcon\\Mvc\\Model\\Resultset ` **getBelongsToRecords** (*string* $method, *string* $modelName, *string* $modelRelation, :doc:`Phalcon\\Mvc\\Model ` $record, *array* $parameters) + +Gets belongsTo related records from a model + + + +public :doc:`Phalcon\\Mvc\\Model\\Resultset ` **getHasManyRecords** (*string* $method, *string* $modelName, *string* $modelRelation, :doc:`Phalcon\\Mvc\\Model ` $record, *array* $parameters) + +Gets hasMany related records from a model + + + +public :doc:`Phalcon\\Mvc\\Model\\Resultset ` **getHasOneRecords** (*string* $method, *string* $modelName, *string* $modelRelation, :doc:`Phalcon\\Mvc\\Model ` $record, *array* $parameters) + +Gets belongsTo related records from a model + + + +public *array* **getBelongsTo** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Gets belongsTo relations defined on a model + + + +public *array* **getHasMany** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Gets hasMany relations defined on a model + + + +public *array* **getHasOne** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Gets hasOne relations defined on a model + + + +public *array* **getHasOneAndHasMany** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Gets hasOne relations defined on a model + + + +public *array* **getRelations** (*string* $first, *string* $second) + +Query the relations between two models + + + +public :doc:`Phalcon\\Mvc\\Model\\Query ` **createQuery** (*string* $phql) + +Creates a Phalcon\\Mvc\\Model\\Query without execute it + + + +public :doc:`Phalcon\\Mvc\\Model\\Query ` **executeQuery** (*string* $phql, *array* $placeholders) + +Creates a Phalcon\\Mvc\\Model\\Query and execute it + + + diff --git a/zh/api/Phalcon_Mvc_Model_Message.rst b/zh/api/Phalcon_Mvc_Model_Message.rst new file mode 100755 index 000000000000..ff24dcd1d514 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Message.rst @@ -0,0 +1,86 @@ +Class **Phalcon\\Mvc\\Model\\Message** +====================================== + +Encapsulates validation info generated before save/delete records fails + +.. code-block:: php + + name == 'Peter') { + $text = "A robot cannot be named Peter"; + $field = "name"; + $type = "InvalidValue"; + $message = new Message($text, $field, $type); + $this->appendMessage($message); + } + } + + } + + + +Methods +--------- + +public **__construct** (*string* $message, *string* $field, *string* $type) + +Phalcon\\Mvc\\Model\\Message constructor + + + +public **setType** (*string* $type) + +Sets message type + + + +public *string* **getType** () + +Returns message type + + + +public **setMessage** (*string* $message) + +Sets verbose message + + + +public *string* **getMessage** () + +Returns verbose message + + + +public **setField** (*string* $field) + +Sets field name related to message + + + +public *string* **getField** () + +Returns field name related to message + + + +public *string* **__toString** () + +Magic __toString method returns verbose message + + + +public static :doc:`Phalcon\\Mvc\\Model\\Message ` **__set_state** (*array* $message) + +Magic __set_state helps to recover messsages from serialization + + + diff --git a/zh/api/Phalcon_Mvc_Model_MetaData.rst b/zh/api/Phalcon_Mvc_Model_MetaData.rst new file mode 100755 index 000000000000..5866a60c19fc --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_MetaData.rst @@ -0,0 +1,157 @@ +Class **Phalcon\\Mvc\\Model\\MetaData** +======================================= + +Because Phalcon\\Mvc\\Model requires meta-data like field names, data types, primary keys, etc. this component collect them and store for further querying by Phalcon\\Model\\Base. Phalcon\\Mvc\\Model\\MetaData can also use adapters to store temporarily or permanently the meta-data. A standard Phalcon\\Mvc\\Model\\MetaData can be used to query model attributes: + +.. code-block:: php + + getAttributes(new Robots()); + print_r($attributes); + + + +Constants +--------- + +*integer* **MODELS_ATTRIBUTES** + +*integer* **MODELS_PRIMARY_KEY** + +*integer* **MODELS_NON_PRIMARY_KEY** + +*integer* **MODELS_NOT_NULL** + +*integer* **MODELS_DATA_TYPES** + +*integer* **MODELS_DATA_TYPES_NUMERIC** + +*integer* **MODELS_DATE_AT** + +*integer* **MODELS_DATE_IN** + +*integer* **MODELS_IDENTITY_COLUMN** + +*integer* **MODELS_DATA_TYPES_BIND** + +*integer* **MODELS_AUTOMATIC_DEFAULT_INSERT** + +*integer* **MODELS_AUTOMATIC_DEFAULT_UPDATE** + +Methods +--------- + +protected **_initializeMetaData** () + +Initialize the metadata for certain table + + + +public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index) + +Reads meta-data for certain model using a MODEL_* constant + + + +public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index, *mixed* $data) + +Writes meta-data for certain model using a MODEL_* constant + + + +public *array* **getAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns table attributes names (fields) + + + +public *array* **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns an array of fields which are part of the primary key + + + +public *array* **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns an arrau of fields which are not part of the primary key + + + +public *array* **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns an array of not null attributes + + + +public *array* **getDataTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns attributes and their data types + + + +public *array* **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns attributes which types are numerical + + + +public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns the name of identity field (if one is present) + + + +public *array* **getBindTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns attributes and their bind data types + + + +public *array* **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns attributes that must be ignored from the INSERT SQL generation + + + +public *array* **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) + +Returns attributes that must be ignored from the UPDATE SQL generation + + + +public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) + +Set the attributes that must be ignored from the INSERT SQL generation + + + +public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) + +Set the attributes that must be ignored from the UPDATE SQL generation + + + +public *boolean* **isEmpty** () + +Checks if the internal meta-data container is empty + + + +public **reset** () + +Resets internal meta-data in order to regenerate it + + + +abstract public **read** () + +... + + +abstract public **write** () + +... + + diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst new file mode 100755 index 000000000000..92e4bad2a673 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Apc.rst @@ -0,0 +1,168 @@ +Class **Phalcon\\Mvc\\Model\\MetaData\\Apc** +============================================ + +*extends* :doc:`Phalcon\\Mvc\\Model\\MetaData ` + +Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch('$PMM$') or apc_fetch('$PMM$my-local-app') + +.. code-block:: php + + 'my-app-id', + 'lifetime' => 86400 + )); + + + +Constants +--------- + +*integer* **MODELS_ATTRIBUTES** + +*integer* **MODELS_PRIMARY_KEY** + +*integer* **MODELS_NON_PRIMARY_KEY** + +*integer* **MODELS_NOT_NULL** + +*integer* **MODELS_DATA_TYPES** + +*integer* **MODELS_DATA_TYPES_NUMERIC** + +*integer* **MODELS_DATE_AT** + +*integer* **MODELS_DATE_IN** + +*integer* **MODELS_IDENTITY_COLUMN** + +*integer* **MODELS_DATA_TYPES_BIND** + +*integer* **MODELS_AUTOMATIC_DEFAULT_INSERT** + +*integer* **MODELS_AUTOMATIC_DEFAULT_UPDATE** + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Mvc\\Model\\MetaData\\Apc constructor + + + +public *array* **read** (*string* $key) + +Reads meta-data from APC + + + +public **write** (*string* $key, *array* $data) + +Writes the meta-data to APC + + + +protected **_initializeMetaData** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Initialize the metadata for certain table + + + +public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index) inherited from Phalcon\\Mvc\\Model\\MetaData + +Reads meta-data for certain model using a MODEL_* constant + + + +public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index, *mixed* $data) inherited from Phalcon\\Mvc\\Model\\MetaData + +Writes meta-data for certain model using a MODEL_* constant + + + +public *array* **getAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns table attributes names (fields) + + + +public *array* **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of fields which are part of the primary key + + + +public *array* **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an arrau of fields which are not part of the primary key + + + +public *array* **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of not null attributes + + + +public *array* **getDataTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their data types + + + +public *array* **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes which types are numerical + + + +public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns the name of identity field (if one is present) + + + +public *array* **getBindTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their bind data types + + + +public *array* **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the INSERT SQL generation + + + +public *array* **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the UPDATE SQL generation + + + +public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the INSERT SQL generation + + + +public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the UPDATE SQL generation + + + +public *boolean* **isEmpty** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Checks if the internal meta-data container is empty + + + +public **reset** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Resets internal meta-data in order to regenerate it + + + diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst new file mode 100644 index 000000000000..1b8d4ec5406a --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Files.rst @@ -0,0 +1,167 @@ +Class **Phalcon\\Mvc\\Model\\MetaData\\Files** +============================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\MetaData ` + +Stores model meta-data in PHP files. + +.. code-block:: php + + 'app/cache/metadata/' + )); + + + +Constants +--------- + +*integer* **MODELS_ATTRIBUTES** + +*integer* **MODELS_PRIMARY_KEY** + +*integer* **MODELS_NON_PRIMARY_KEY** + +*integer* **MODELS_NOT_NULL** + +*integer* **MODELS_DATA_TYPES** + +*integer* **MODELS_DATA_TYPES_NUMERIC** + +*integer* **MODELS_DATE_AT** + +*integer* **MODELS_DATE_IN** + +*integer* **MODELS_IDENTITY_COLUMN** + +*integer* **MODELS_DATA_TYPES_BIND** + +*integer* **MODELS_AUTOMATIC_DEFAULT_INSERT** + +*integer* **MODELS_AUTOMATIC_DEFAULT_UPDATE** + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Mvc\\Model\\MetaData\\Files constructor + + + +public *array* **read** (*unknown* $key) + +Reads meta-data from $_SESSION + + + +public **write** (*string* $key, *array* $data) + +Writes the meta-data to $_SESSION + + + +protected **_initializeMetaData** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Initialize the metadata for certain table + + + +public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index) inherited from Phalcon\\Mvc\\Model\\MetaData + +Reads meta-data for certain model using a MODEL_* constant + + + +public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index, *mixed* $data) inherited from Phalcon\\Mvc\\Model\\MetaData + +Writes meta-data for certain model using a MODEL_* constant + + + +public *array* **getAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns table attributes names (fields) + + + +public *array* **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of fields which are part of the primary key + + + +public *array* **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an arrau of fields which are not part of the primary key + + + +public *array* **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of not null attributes + + + +public *array* **getDataTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their data types + + + +public *array* **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes which types are numerical + + + +public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns the name of identity field (if one is present) + + + +public *array* **getBindTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their bind data types + + + +public *array* **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the INSERT SQL generation + + + +public *array* **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the UPDATE SQL generation + + + +public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the INSERT SQL generation + + + +public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the UPDATE SQL generation + + + +public *boolean* **isEmpty** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Checks if the internal meta-data container is empty + + + +public **reset** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Resets internal meta-data in order to regenerate it + + + diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst new file mode 100755 index 000000000000..3c1627b4f40b --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Memory.rst @@ -0,0 +1,158 @@ +Class **Phalcon\\Mvc\\Model\\MetaData\\Memory** +=============================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\MetaData ` + +Stores model meta-data in memory. Data will be erased when the request finishes + + +Constants +--------- + +*integer* **MODELS_ATTRIBUTES** + +*integer* **MODELS_PRIMARY_KEY** + +*integer* **MODELS_NON_PRIMARY_KEY** + +*integer* **MODELS_NOT_NULL** + +*integer* **MODELS_DATA_TYPES** + +*integer* **MODELS_DATA_TYPES_NUMERIC** + +*integer* **MODELS_DATE_AT** + +*integer* **MODELS_DATE_IN** + +*integer* **MODELS_IDENTITY_COLUMN** + +*integer* **MODELS_DATA_TYPES_BIND** + +*integer* **MODELS_AUTOMATIC_DEFAULT_INSERT** + +*integer* **MODELS_AUTOMATIC_DEFAULT_UPDATE** + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Mvc\\Model\\MetaData\\Memory constructor + + + +public *array* **read** (*unknown* $key) + +Reads the meta-data from temporal memory + + + +public **write** () + +Writes the meta-data to temporal memory + + + +protected **_initializeMetaData** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Initialize the metadata for certain table + + + +public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index) inherited from Phalcon\\Mvc\\Model\\MetaData + +Reads meta-data for certain model using a MODEL_* constant + + + +public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index, *mixed* $data) inherited from Phalcon\\Mvc\\Model\\MetaData + +Writes meta-data for certain model using a MODEL_* constant + + + +public *array* **getAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns table attributes names (fields) + + + +public *array* **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of fields which are part of the primary key + + + +public *array* **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an arrau of fields which are not part of the primary key + + + +public *array* **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of not null attributes + + + +public *array* **getDataTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their data types + + + +public *array* **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes which types are numerical + + + +public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns the name of identity field (if one is present) + + + +public *array* **getBindTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their bind data types + + + +public *array* **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the INSERT SQL generation + + + +public *array* **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the UPDATE SQL generation + + + +public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the INSERT SQL generation + + + +public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the UPDATE SQL generation + + + +public *boolean* **isEmpty** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Checks if the internal meta-data container is empty + + + +public **reset** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Resets internal meta-data in order to regenerate it + + + diff --git a/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst b/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst new file mode 100755 index 000000000000..6879066071e7 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_MetaData_Session.rst @@ -0,0 +1,167 @@ +Class **Phalcon\\Mvc\\Model\\MetaData\\Session** +================================================ + +*extends* :doc:`Phalcon\\Mvc\\Model\\MetaData ` + +Stores model meta-data in session. Data will erase when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION['$PMM$'] + +.. code-block:: php + + 'my-app-id' + )); + + + +Constants +--------- + +*integer* **MODELS_ATTRIBUTES** + +*integer* **MODELS_PRIMARY_KEY** + +*integer* **MODELS_NON_PRIMARY_KEY** + +*integer* **MODELS_NOT_NULL** + +*integer* **MODELS_DATA_TYPES** + +*integer* **MODELS_DATA_TYPES_NUMERIC** + +*integer* **MODELS_DATE_AT** + +*integer* **MODELS_DATE_IN** + +*integer* **MODELS_IDENTITY_COLUMN** + +*integer* **MODELS_DATA_TYPES_BIND** + +*integer* **MODELS_AUTOMATIC_DEFAULT_INSERT** + +*integer* **MODELS_AUTOMATIC_DEFAULT_UPDATE** + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Mvc\\Model\\MetaData\\Session constructor + + + +public *array* **read** (*unknown* $key) + +Reads meta-data from $_SESSION + + + +public **write** (*string* $key, *array* $data) + +Writes the meta-data to $_SESSION + + + +protected **_initializeMetaData** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Initialize the metadata for certain table + + + +public **readMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index) inherited from Phalcon\\Mvc\\Model\\MetaData + +Reads meta-data for certain model using a MODEL_* constant + + + +public **writeMetaDataIndex** (:doc:`Phalcon\\Mvc\\Model ` $model, *int* $index, *mixed* $data) inherited from Phalcon\\Mvc\\Model\\MetaData + +Writes meta-data for certain model using a MODEL_* constant + + + +public *array* **getAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns table attributes names (fields) + + + +public *array* **getPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of fields which are part of the primary key + + + +public *array* **getNonPrimaryKeyAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an arrau of fields which are not part of the primary key + + + +public *array* **getNotNullAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns an array of not null attributes + + + +public *array* **getDataTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their data types + + + +public *array* **getDataTypesNumeric** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes which types are numerical + + + +public *string* **getIdentityField** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns the name of identity field (if one is present) + + + +public *array* **getBindTypes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes and their bind data types + + + +public *array* **getAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the INSERT SQL generation + + + +public *array* **getAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model) inherited from Phalcon\\Mvc\\Model\\MetaData + +Returns attributes that must be ignored from the UPDATE SQL generation + + + +public **setAutomaticCreateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the INSERT SQL generation + + + +public **setAutomaticUpdateAttributes** (:doc:`Phalcon\\Mvc\\Model ` $model, *array* $attributes) inherited from Phalcon\\Mvc\\Model\\MetaData + +Set the attributes that must be ignored from the UPDATE SQL generation + + + +public *boolean* **isEmpty** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Checks if the internal meta-data container is empty + + + +public **reset** () inherited from Phalcon\\Mvc\\Model\\MetaData + +Resets internal meta-data in order to regenerate it + + + diff --git a/zh/api/Phalcon_Mvc_Model_Query.rst b/zh/api/Phalcon_Mvc_Model_Query.rst new file mode 100755 index 000000000000..1e3e1427a830 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Query.rst @@ -0,0 +1,176 @@ +Class **Phalcon\\Mvc\\Model\\Query** +==================================== + +This class takes a PHQL intermediate representation and executes it. + +.. code-block:: php + + executeQuery($phql, array( + 'name' => 'Lamborghini' + )); + + foreach ($result as $row) { + echo "Name: ", $row->cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } + + + +Methods +--------- + +public **__construct** (*string* $phql) + +Phalcon\\Mvc\\Model\\Query constructor + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injection container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the dependency injection container + + + +protected *string* **_getQualified** () + +Replaces the model's name to its source name in a qualifed-name expression + + + +protected *string* **_getCallArgument** () + +Resolves a expression in a single call argument + + + +protected *string* **_getFunctionCall** () + +Resolves a expression in a single call argument + + + +protected *string* **_getExpression** () + +Resolves an expression from its intermediate code into a string + + + +protected *array* **_getSelectColumn** () + +Resolves a column from its intermediate representation into an array used to determine if the resulset produced will be simple or complex + + + +protected *string* **_getTable** () + +Resolves a table in a SELECT statement checking if the model exists + + + +protected *array* **_getJoin** () + +Resolves a JOIN clause checking if the associated models exist + + + +protected *string* **_getJoinType** () + +Resolves a JOIN type + + + +protected *array* **_getJoins** () + +Resolves all the JOINS in a SELECT statement + + + +protected *string* **_getLimitClause** () + +Returns a processed limit clause for a SELECT statement + + + +protected *string* **_getOrderClause** () + +Returns a processed order clause for a SELECT statement + + + +protected *string* **_getGroupClause** () + +Returns a processed group clause for a SELECT statement + + + +protected **_prepareSelect** () + +Analyzes a SELECT intermediate code and produces an array to be executed later + + + +protected *array* **_prepareInsert** () + +Analyzes an INSERT intermediate code and produces an array to be executed later + + + +protected *array* **_prepareUpdate** () + +Analyzes an UPDATE intermediate code and produces an array to be executed later + + + +protected *array* **_prepareDelete** () + +Analyzes a DELETE intermediate code and produces an array to be executed later + + + +public *array* **parse** (:doc:`Phalcon\\Mvc\\Model ` $manager) + +Parses the intermediate code produced by Phalcon\\Mvc\\Model\\Query\\Lang generating another intermediate representation that could be executed by Phalcon\\Mvc\\Model\\Query + + + +protected :doc:`Phalcon\\Mvc\\Model\\Resultset ` **_executeSelect** () + +Executes the SELECT intermediate representation producing a Phalcon\\Mvc\\Model\\Resultset + + + +protected :doc:`Phalcon\\Mvc\\Model\\Query\\Status ` **_executeInsert** () + +Executes the INSERT intermediate representation producing a Phalcon\\Mvc\\Model\\Query\\Status + + + +protected :doc:`Phalcon\\Mvc\\Model\\Query\\Status ` **_executeUpdate** () + +Executes the UPDATE intermediate representation producing a Phalcon\\Mvc\\Model\\Query\\Status + + + +protected :doc:`Phalcon\\Mvc\\Model\\Query\\Status ` **_executeDelete** () + +Executes the DELETE intermediate representation producing a Phalcon\\Mvc\\Model\\Query\\Status + + + +public *mixed* **execute** (*array* $placeholders) + +Executes a parsed PHQL statement + + + diff --git a/zh/api/Phalcon_Mvc_Model_Query_Lang.rst b/zh/api/Phalcon_Mvc_Model_Query_Lang.rst new file mode 100644 index 000000000000..23db9c2543b8 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Query_Lang.rst @@ -0,0 +1,22 @@ +Class **Phalcon\\Mvc\\Model\\Query\\Lang** +========================================== + +PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. It allows Phalcon to offer a unified SQL language to the developer, while internally doing all the work of translating PHQL instructions to the most optimal SQL instructions depending on the RDBMS type associated with a model. To achieve the highest performance possible, we wrote a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe. + +.. code-block:: php + + modelsManager->executeQuery($phql, array( + 'id' => 100, + 'name' => 'Astroy Boy', + 'type' => 'mechanical', + 'year' => 1959 + )); + + \//Check if the update was successful + if($status->success()==true){ + echo 'OK'; + } + + + +Methods +--------- + +public **__construct** (*boolean* $success, :doc:`Phalcon\\Mvc\\Model ` $model) + + + + + +public :doc:`Phalcon\\Mvc\\Model ` **getModel** () + +Returns the model which executed the action + + + +public :doc:`Phalcon\\Mvc\\Model\\Message ` [] **getMessages** () + +Returns the messages produced by a operation failed + + + +public *boolean* **success** () + +Allows to check if the executed operation was successful + + + diff --git a/zh/api/Phalcon_Mvc_Model_Resultset.rst b/zh/api/Phalcon_Mvc_Model_Resultset.rst new file mode 100755 index 000000000000..5ff40cfb936f --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Resultset.rst @@ -0,0 +1,119 @@ +Class **Phalcon\\Mvc\\Model\\Resultset** +======================================== + +This component allows to Phalcon\\Mvc\\Model returns large resulsets with the minimum memory consumption Resulsets can be traversed using a standard foreach or a while statement. If a resultset is serialized it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before serializing. + +.. code-block:: php + + "name")); + foreach($robots as $robot){ + echo $robot->name, "\n"; + } + + //Using a while + $robots = $Robots::find(array("type='virtual'", "order" => "name")); + $robots->rewind(); + while($robots->valid()){ + $robot = $robots->current(); + echo $robot->name, "\n"; + $robots->next(); + } + + + +Methods +--------- + +public **next** () + +Moves cursor to next row in the resultset + + + +public *int* **key** () + +Gets pointer number of active row in the resultset + + + +public **rewind** () + +Rewinds resultset to its beginning + + + +public **seek** (*int* $position) + +Changes internal pointer to a specific position in the resultset + + + +public *int* **count** () + +Counts how many rows are in the resultset + + + +public *boolean* **offsetExists** (*int* $index) + +Checks whether offset exists in the resultset + + + +public :doc:`Phalcon\\Mvc\\Model ` **offsetGet** (*int* $index) + +Gets row in a specific position of the resultset + + + +public **offsetSet** (*int* $index, :doc:`Phalcon\\Mvc\\Model ` $value) + +Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public **offsetUnset** (*int* $offset) + +Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public :doc:`Phalcon\\Mvc\\Model ` **getFirst** () + +Get first row in the resultset + + + +public :doc:`Phalcon\\Mvc\\Model ` **getLast** () + +Get last row in the resultset + + + +public **setIsFresh** (*boolean* $isFresh) + +Set if the resultset is fresh or an old one cached + + + +public *boolean* **isFresh** () + +Tell if the resultset if fresh or an old one cached + + + +public :doc:`Phalcon\\Cache\\Backend ` **getCache** () + +Returns the associated cache for the resultset + + + +public *object* **current** () + +Returns current row in the resultset + + + diff --git a/zh/api/Phalcon_Mvc_Model_Resultset_Complex.rst b/zh/api/Phalcon_Mvc_Model_Resultset_Complex.rst new file mode 100644 index 000000000000..9cb79205b9eb --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Resultset_Complex.rst @@ -0,0 +1,127 @@ +Class **Phalcon\\Mvc\\Model\\Resultset\\Complex** +================================================= + +*extends* :doc:`Phalcon\\Mvc\\Model\\Resultset ` + +*implements* Iterator, Traversable, SeekableIterator, Countable, ArrayAccess, Serializable + +Complex resultsets may include complete objects and scalar values. This class builds every complex row as the're required + + +Methods +--------- + +public **__construct** (*array* $columnsTypes, :doc:`Phalcon\\Db\\Result\\Pdo ` $result, :doc:`Phalcon\\Cache\\Backend ` $cache) + +Phalcon\\Mvc\\Model\\Resultset\\Complex constructor + + + +public *boolean* **valid** () + +Check whether internal resource has rows to fetch + + + +public *string* **serialize** () + +Serializing a resultset will dump all related rows into a big array + + + +public **unserialize** (*string* $data) + +Unserializing a resultset will allow to only works on the rows present in the saved state + + + +public **next** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Moves cursor to next row in the resultset + + + +public *int* **key** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Gets pointer number of active row in the resultset + + + +public **rewind** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Rewinds resultset to its beginning + + + +public **seek** (*int* $position) inherited from Phalcon\\Mvc\\Model\\Resultset + +Changes internal pointer to a specific position in the resultset + + + +public *int* **count** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Counts how many rows are in the resultset + + + +public *boolean* **offsetExists** (*int* $index) inherited from Phalcon\\Mvc\\Model\\Resultset + +Checks whether offset exists in the resultset + + + +public :doc:`Phalcon\\Mvc\\Model ` **offsetGet** (*int* $index) inherited from Phalcon\\Mvc\\Model\\Resultset + +Gets row in a specific position of the resultset + + + +public **offsetSet** (*int* $index, :doc:`Phalcon\\Mvc\\Model ` $value) inherited from Phalcon\\Mvc\\Model\\Resultset + +Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public **offsetUnset** (*int* $offset) inherited from Phalcon\\Mvc\\Model\\Resultset + +Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public :doc:`Phalcon\\Mvc\\Model ` **getFirst** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Get first row in the resultset + + + +public :doc:`Phalcon\\Mvc\\Model ` **getLast** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Get last row in the resultset + + + +public **setIsFresh** (*boolean* $isFresh) inherited from Phalcon\\Mvc\\Model\\Resultset + +Set if the resultset is fresh or an old one cached + + + +public *boolean* **isFresh** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Tell if the resultset if fresh or an old one cached + + + +public :doc:`Phalcon\\Cache\\Backend ` **getCache** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Returns the associated cache for the resultset + + + +public *object* **current** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Returns current row in the resultset + + + diff --git a/zh/api/Phalcon_Mvc_Model_Resultset_Simple.rst b/zh/api/Phalcon_Mvc_Model_Resultset_Simple.rst new file mode 100644 index 000000000000..c54b125493d8 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Resultset_Simple.rst @@ -0,0 +1,127 @@ +Class **Phalcon\\Mvc\\Model\\Resultset\\Simple** +================================================ + +*extends* :doc:`Phalcon\\Mvc\\Model\\Resultset ` + +*implements* Iterator, Traversable, SeekableIterator, Countable, ArrayAccess, Serializable + +Simple resultsets only contains a complete object. This class builds every complete object as it's required + + +Methods +--------- + +public **__construct** (:doc:`Phalcon\\Mvc\\Model ` $model, :doc:`Phalcon\\Db\\Result\\Pdo ` $result, :doc:`Phalcon\\Cache\\Backend ` $cache) + +Phalcon\\Mvc\\Model\\Resultset\\Simple constructor + + + +public *boolean* **valid** () + +Check whether internal resource has rows to fetch + + + +public *string* **serialize** () + +Serializing a resultset will dump all related rows into a big array + + + +public **unserialize** (*string* $data) + +Unserializing a resultset will allow to only works on the rows present in the saved state + + + +public **next** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Moves cursor to next row in the resultset + + + +public *int* **key** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Gets pointer number of active row in the resultset + + + +public **rewind** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Rewinds resultset to its beginning + + + +public **seek** (*int* $position) inherited from Phalcon\\Mvc\\Model\\Resultset + +Changes internal pointer to a specific position in the resultset + + + +public *int* **count** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Counts how many rows are in the resultset + + + +public *boolean* **offsetExists** (*int* $index) inherited from Phalcon\\Mvc\\Model\\Resultset + +Checks whether offset exists in the resultset + + + +public :doc:`Phalcon\\Mvc\\Model ` **offsetGet** (*int* $index) inherited from Phalcon\\Mvc\\Model\\Resultset + +Gets row in a specific position of the resultset + + + +public **offsetSet** (*int* $index, :doc:`Phalcon\\Mvc\\Model ` $value) inherited from Phalcon\\Mvc\\Model\\Resultset + +Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public **offsetUnset** (*int* $offset) inherited from Phalcon\\Mvc\\Model\\Resultset + +Resulsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public :doc:`Phalcon\\Mvc\\Model ` **getFirst** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Get first row in the resultset + + + +public :doc:`Phalcon\\Mvc\\Model ` **getLast** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Get last row in the resultset + + + +public **setIsFresh** (*boolean* $isFresh) inherited from Phalcon\\Mvc\\Model\\Resultset + +Set if the resultset is fresh or an old one cached + + + +public *boolean* **isFresh** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Tell if the resultset if fresh or an old one cached + + + +public :doc:`Phalcon\\Cache\\Backend ` **getCache** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Returns the associated cache for the resultset + + + +public *object* **current** () inherited from Phalcon\\Mvc\\Model\\Resultset + +Returns current row in the resultset + + + diff --git a/zh/api/Phalcon_Mvc_Model_Row.rst b/zh/api/Phalcon_Mvc_Model_Row.rst new file mode 100755 index 000000000000..1dfcb49f54e8 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Row.rst @@ -0,0 +1,40 @@ +Class **Phalcon\\Mvc\\Model\\Row** +================================== + +*implements* ArrayAccess + +This component allows Phalcon\\Mvc\\Model to return rows without an associated entity. This objects implements the ArrayAccess interfase to allow access the object as object->x or array[x]. + + +Methods +--------- + +public **setForceExists** () + +... + + +public *boolean* **offsetExists** (*int* $index) + +Checks whether offset exists in the row + + + +public *string|Phalcon\Mvc\Model* **offsetGet** (*int* $index) + +Gets row in a specific position of the row + + + +public **offsetSet** (*int* $index, :doc:`Phalcon\\Mvc\\Model ` $value) + +Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + +public **offsetUnset** (*int* $offset) + +Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface + + + diff --git a/zh/api/Phalcon_Mvc_Model_Transaction.rst b/zh/api/Phalcon_Mvc_Model_Transaction.rst new file mode 100755 index 000000000000..af6eb5c86173 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Transaction.rst @@ -0,0 +1,112 @@ +Class **Phalcon\\Mvc\\Model\\Transaction** +========================================== + +Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Phalcon\\Transaction is intended to be used with Phalcon_Model_Base. Phalcon Transactions should be created using Phalcon\\Transaction\\Manager. + +.. code-block:: php + + setTransaction($transaction); + $robot->name = 'WALL·E'; + $robot->created_at = date('Y-m-d'); + if($robot->save()==false){ + $transaction->rollback("Can't save robot"); + } + + $robotPart = new RobotParts(); + $robotPart->setTransaction($transaction); + $robotPart->type = 'head'; + if($robotPart->save()==false){ + $transaction->rollback("Can't save robot part"); + } + + $transaction->commit(); + + } + catch(Phalcon\Mvc\Model\Transaction\Failed $e){ + echo 'Failed, reason: ', $e->getMessage(); + } + + + +Methods +--------- + +public **__construct** (:doc:`Phalcon\\DI ` $dependencyInjector, *boolean* $autoBegin) + +Phalcon\\Mvc\\Model\\Transaction constructor + + + +public **setTransactionManager** (:doc:`Phalcon\\Mvc\\Model\\Transaction\\Manager ` $manager) + +Sets transaction manager related to the transaction + + + +public *boolean* **begin** () + +Starts the transaction + + + +public *boolean* **commit** () + +Commits the transaction + + + +public *boolean* **rollback** (*string* $rollbackMessage, :doc:`Phalcon\\Mvc\\Model ` $rollbackRecord) + +Rollbacks the transaction + + + +public *string* **getConnection** () + +Returns connection related to transaction + + + +public **setIsNewTransaction** (*boolean* $isNew) + +Sets if is a reused transaction or new once + + + +public **setRollbackOnAbort** (*boolean* $rollbackOnAbort) + +Sets flag to rollback on abort the HTTP connection + + + +public *boolean* **isManaged** () + +Checks whether transaction is managed by a transaction manager + + + +public *array* **getMessages** () + +Returns validations messages from last save try + + + +public *boolean* **isValid** () + +Checks whether internal connection is under an active transaction + + + +public **setRollbackedRecord** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Sets object which generates rollback action + + + diff --git a/zh/api/Phalcon_Mvc_Model_Transaction_Exception.rst b/zh/api/Phalcon_Mvc_Model_Transaction_Exception.rst new file mode 100755 index 000000000000..0f1818f1cbbc --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Transaction_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Model\\Transaction\\Exception** +===================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Model\\Transaction will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Model_Transaction_Failed.rst b/zh/api/Phalcon_Mvc_Model_Transaction_Failed.rst new file mode 100755 index 000000000000..c6dceba05c5c --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Transaction_Failed.rst @@ -0,0 +1,83 @@ +Class **Phalcon\\Mvc\\Model\\Transaction\\Failed** +================================================== + +*extends* Exception + +Phalcon\\Mvc\\Model\\Transaction\\Failed will be thrown to exit a try/catch block for transactions + + +Methods +--------- + +public **__construct** (*string* $message, :doc:`Phalcon\\Mvc\\Model ` $record) + +Phalcon\\Mvc\\Model\\Transaction\\Failed constructor + + + +public *string* **getRecordMessages** () + +Returns validation record messages which stop the transaction + + + +public :doc:`Phalcon\\Mvc\\Model ` **getRecord** () + +Returns validation record messages which stop the transaction + + + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst b/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst new file mode 100755 index 000000000000..7501074506b8 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Transaction_Manager.rst @@ -0,0 +1,115 @@ +Class **Phalcon\\Mvc\\Model\\Transaction\\Manager** +=================================================== + +A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. This class manages the objects that compose a transaction. A trasaction produces a unique connection that is passed to every object part of the transaction. + +.. code-block:: php + + get(); + + $robot = new Robots(); + $robot->setTransaction($transaction); + $robot->name = 'WALL·E'; + $robot->created_at = date('Y-m-d'); + if($robot->save()==false){ + $transaction->rollback("Can't save robot"); + } + + $robotPart = new RobotParts(); + $robotPart->setTransaction($transaction); + $robotPart->type = 'head'; + if($robotPart->save()==false){ + $transaction->rollback("Can't save robot part"); + } + + $transaction->commit(); + + } + catch(Phalcon\Mvc\Model\Transaction\Failed $e){ + echo 'Failed, reason: ', $e->getMessage(); + } + + + +Methods +--------- + +public **__construct** (:doc:`Phalcon\\DI ` $dependencyInjector) + + + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injection container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the dependency injection container + + + +public *boolean* **has** () + +Checks whether manager has an active transaction + + + +public :doc:`Phalcon\\Mvc\\Model\\Transaction ` **get** (*boolean* $autoBegin) + +Returns a new Phalcon\\Mvc\\Model\\Transaction or an already created once + + + +public **rollbackPendent** () + +Rollbacks active transactions within the manager + + + +public **commit** () + +Commmits active transactions within the manager + + + +public **rollback** (*boolean* $collect) + +Rollbacks active transactions within the manager Collect will remove transaction from the manager + + + +public **notifyRollback** (:doc:`Phalcon\\Mvc\\Model\\Transaction ` $transaction) + +Notifies the manager about a rollbacked transaction + + + +public **notifyCommit** (:doc:`Phalcon\\Mvc\\Model\\Transaction ` $transaction) + +Notifies the manager about a commited transaction + + + +private **_collectTransaction** () + +... + + +public **collectTransactions** () + +Remove all the transactions from the manager + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator.rst b/zh/api/Phalcon_Mvc_Model_Validator.rst new file mode 100755 index 000000000000..4d07066e93a1 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator.rst @@ -0,0 +1,45 @@ +Class **Phalcon\\Mvc\\Model\\Validator** +======================================== + +This is a base class for Phalcon\\Mvc\\Model validators + + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () + +Appends a message to the validator + + + +public *array* **getMessages** () + +Returns messages generated by the validator + + + +protected *array* **getOptions** () + +Returns all the options from the validator + + + +protected *mixed* **getOption** () + +Returns an option + + + +protected *boolean* **isSetOption** () + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Email.rst b/zh/api/Phalcon_Mvc_Model_Validator_Email.rst new file mode 100755 index 000000000000..2921fe9d38c6 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_Email.rst @@ -0,0 +1,75 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\Email** +=============================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Allows to validate if email fields has correct values + +.. code-block:: php + + validate(new EmailValidator(array( + 'field' => 'electronic_mail' + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst b/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst new file mode 100755 index 000000000000..08e8e920e343 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_Exclusionin.rst @@ -0,0 +1,76 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\Exclusionin** +===================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Phalcon\\Mvc\\Model\\Validator\\ExclusionIn Check if a value is not included into a list of values + +.. code-block:: php + + validate(new ExclusionInValidator(array( + 'field' => 'status', + 'domain' => array('A', 'I') + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst b/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst new file mode 100755 index 000000000000..b55a63cd73a9 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_Inclusionin.rst @@ -0,0 +1,76 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\Inclusionin** +===================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Phalcon\\Mvc\\Model\\Validator\\InclusionIn Check if a value is included into a list of values + +.. code-block:: php + + validate(new InclusionInValidator(array( + 'field' => 'status', + 'domain' => array('A', 'I') + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst b/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst new file mode 100755 index 000000000000..0a468b48d476 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_Numericality.rst @@ -0,0 +1,75 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\Numericality** +====================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Allows to validate if a field has a valid numeric format + +.. code-block:: php + + validate(new NumericalityValidator(array( + 'field' => 'price' + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst b/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst new file mode 100644 index 000000000000..bb8d96139bcb --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_PresenceOf.rst @@ -0,0 +1,76 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\PresenceOf** +==================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Allows to validate if a filed have a value different of null and empty string ("") + +.. code-block:: php + + validate(new PresenceOf(array( + 'field' => 'name', + 'message' => 'The name is required' + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst b/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst new file mode 100755 index 000000000000..26132bdd2375 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_Regex.rst @@ -0,0 +1,76 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\Regex** +=============================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Allows to validate if the value of a field matches a regular expression + +.. code-block:: php + + validate(new RegexValidator(array( + 'field' => 'created_at', + 'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/' + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst b/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst new file mode 100644 index 000000000000..65eecfc554a4 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_StringLength.rst @@ -0,0 +1,77 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\StringLength** +====================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Simply validates specified string length constraints + +.. code-block:: php + + validate(new StringLengthValidator(array( + 'field' => 'name_last', + 'max' => 50, //we don't like really long names + 'min' => 2, //we want more than just their initials + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (*unknown* $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst b/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst new file mode 100755 index 000000000000..9c0ed1c7ed60 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Model_Validator_Uniqueness.rst @@ -0,0 +1,75 @@ +Class **Phalcon\\Mvc\\Model\\Validator\\Uniqueness** +==================================================== + +*extends* :doc:`Phalcon\\Mvc\\Model\\Validator ` + +Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table + +.. code-block:: php + + validate(new UniquenessValidator(array( + 'field' => 'email' + ))); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + + + +Methods +--------- + +public *boolean* **validate** (:doc:`Phalcon\\Mvc\\Model ` $record) + +Executes the validator + + + +public **__construct** (*array* $options) inherited from Phalcon\\Mvc\\Model\\Validator + +Phalcon\\Mvc\\Model\\Validator constructor + + + +protected **appendMessage** () inherited from Phalcon\\Mvc\\Model\\Validator + +Appends a message to the validator + + + +public *array* **getMessages** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns messages generated by the validator + + + +protected *array* **getOptions** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns all the options from the validator + + + +protected *mixed* **getOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Returns an option + + + +protected *boolean* **isSetOption** () inherited from Phalcon\\Mvc\\Model\\Validator + +Check whether a option has been defined in the validator options + + + diff --git a/zh/api/Phalcon_Mvc_Router.rst b/zh/api/Phalcon_Mvc_Router.rst new file mode 100755 index 000000000000..33d3dd07879f --- /dev/null +++ b/zh/api/Phalcon_Mvc_Router.rst @@ -0,0 +1,180 @@ +Class **Phalcon\\Mvc\\Router** +============================== + +Phalcon\\Mvc\\Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request + +.. code-block:: php + + handle(); + echo $router->getControllerName(); + + + +Methods +--------- + +public **__construct** (*boolean* $defaultRoutes) + +Phalcon\\Mvc\\Router constructor + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the internal dependency injector + + + +protected *string* **_getRewriteUri** () + +Get rewrite info + + + +public **setDefaultModule** (*string* $moduleName) + +Sets the name of the default module + + + +public **setDefaultController** (*string* $controllerName) + +Sets the default controller name + + + +public **setDefaultAction** (*string* $actionName) + +Sets the default action name + + + +public **setDefaults** (*array* $defaults) + +Sets an array of default paths + + + +public **handle** (*string* $uri) + +Handles routing information received from the rewrite engine + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **add** (*string* $pattern, *string/array* $paths, *string* $httpMethods) + +Add a route to the router on any HTTP method + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **addGet** (*string* $pattern, *string/array* $paths) + +Add a route to the router that only match if the HTTP method is GET + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **addPost** (*string* $pattern, *string/array* $paths) + +Add a route to the router that only match if the HTTP method is POST + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **addPut** (*string* $pattern, *string/array* $paths) + +Add a route to the router that only match if the HTTP method is PUT + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **addDelete** (*string* $pattern, *string/array* $paths) + +Add a route to the router that only match if the HTTP method is DELETE + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **addOptions** (*string* $pattern, *string/array* $paths) + +Add a route to the router that only match if the HTTP method is OPTIONS + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **addHead** (*string* $pattern, *string/array* $paths) + +Add a route to the router that only match if the HTTP method is HEAD + + + +public **clear** () + +Removes all the pre-defined routes + + + +public *string* **getModuleName** () + +Returns proccesed module name + + + +public *string* **getControllerName** () + +Returns proccesed controller name + + + +public *string* **getActionName** () + +Returns proccesed action name + + + +public *array* **getParams** () + +Returns proccesed extra params + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **getMatchedRoute** () + +Returns the route that matchs the handled URI + + + +public *array* **getMatches** () + +Return the sub expressions in the regular expression matched + + + +public *bool* **wasMatched** () + +Check if the router macthes any of the defined routes + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` [] **getRoutes** () + +Return all the routes defined in the router + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **getRouteById** (*unknown* $id) + +Returns a route object by its id + + + +public :doc:`Phalcon\\Mvc\\Router\\Route ` **getRouteByName** (*unknown* $name) + +Returns a route object by its name + + + diff --git a/zh/api/Phalcon_Mvc_Router_Exception.rst b/zh/api/Phalcon_Mvc_Router_Exception.rst new file mode 100644 index 000000000000..99468f0124e3 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Router_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Router\\Exception** +========================================= + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Router will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_Router_Route.rst b/zh/api/Phalcon_Mvc_Router_Route.rst new file mode 100644 index 000000000000..0e79974a838a --- /dev/null +++ b/zh/api/Phalcon_Mvc_Router_Route.rst @@ -0,0 +1,87 @@ +Class **Phalcon\\Mvc\\Router\\Route** +===================================== + +This class represents every route defined in the router. + + +Methods +--------- + +public **__construct** (*string* $pattern, *array* $paths, *array|string* $httpMethods) + +Phalcon\\Mvc\\Router\\Route constructor + + + +public *string* **compilePattern** (*string* $pattern) + +Replaces placeholders from pattern returning a valid PCRE regular expression + + + +public **via** (*string|array* $httpMethods) + +Set one or more HTTP methods that constraint the matching of the route + + + +public **reConfigure** (*string* $pattern, *array* $paths) + +Reconfigure the route adding a new pattern and a set of paths + + + +public *string* **getName** () + +Returns the route's name + + + +public **setName** (*string* $name) + +Sets the route's name + + + +public **setHttpMethods** (*string|array* $httpMethods) + +Sets a set of HTTP methods that constraint the matching of the route + + + +public *string* **getRouteId** () + +Returns the route's id + + + +public *string* **getPattern** () + +Returns the route's pattern + + + +public *string* **getCompiledPattern** () + +Returns the route's pattern + + + +public *array* **getPaths** () + +Returns the paths + + + +public *string|array* **getHttpMethods** () + +Returns the HTTP methods that constraint matching the route + + + +public static **reset** () + +Resets the internal route id generator + + + diff --git a/zh/api/Phalcon_Mvc_Url.rst b/zh/api/Phalcon_Mvc_Url.rst new file mode 100644 index 000000000000..dccf26725db6 --- /dev/null +++ b/zh/api/Phalcon_Mvc_Url.rst @@ -0,0 +1,82 @@ +Class **Phalcon\\Mvc\\Url** +=========================== + +This components aids in the generation of: URIs, URLs and Paths + +.. code-block:: php + + get('products/edit/1'); + + //Generate a url for a predefined route + echo $url->get(array('for' => 'blog-post', 'title' => 'some-cool-stuff', 'year' => '2012')); + + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the DependencyInjector container + + + +public **setBaseUri** (*string* $baseUri) + +Sets a prefix to all the urls generated + +.. code-block:: php + + setBasePath('/invo/'); + + + + +public *string* **getBaseUri** () + +Returns the prefix for all the generated urls. By default / + + + +public **setBasePath** (*string* $basePath) + +Sets a base paths for all the generated paths + +.. code-block:: php + + setBasePath('/var/www/'); + + + + +public *string* **getBasePath** () + +Returns a base path + + + +public *string* **get** (*string|array* $uri) + +Generates a URL + + + +public *string* **path** (*string* $path) + +Generates a local path + + + diff --git a/zh/api/Phalcon_Mvc_Url_Exception.rst b/zh/api/Phalcon_Mvc_Url_Exception.rst new file mode 100644 index 000000000000..a935b720a68c --- /dev/null +++ b/zh/api/Phalcon_Mvc_Url_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\Url\\Exception** +====================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Mvc\\Url will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Mvc_User_Component.rst b/zh/api/Phalcon_Mvc_User_Component.rst new file mode 100644 index 000000000000..c952666d676f --- /dev/null +++ b/zh/api/Phalcon_Mvc_User_Component.rst @@ -0,0 +1,41 @@ +Class **Phalcon\\Mvc\\User\\Component** +======================================= + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +This class can be used to provide user components easy access to services in the application + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_User_Module.rst b/zh/api/Phalcon_Mvc_User_Module.rst new file mode 100644 index 000000000000..4492414bda19 --- /dev/null +++ b/zh/api/Phalcon_Mvc_User_Module.rst @@ -0,0 +1,41 @@ +Class **Phalcon\\Mvc\\User\\Module** +==================================== + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +This class can be used to provide user components easy access to services in the application + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_User_Plugin.rst b/zh/api/Phalcon_Mvc_User_Plugin.rst new file mode 100644 index 000000000000..99e1b43ccdee --- /dev/null +++ b/zh/api/Phalcon_Mvc_User_Plugin.rst @@ -0,0 +1,41 @@ +Class **Phalcon\\Mvc\\User\\Plugin** +==================================== + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +This class can be used to provide user components easy access to services in the application + + +Methods +--------- + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_View.rst b/zh/api/Phalcon_Mvc_View.rst new file mode 100755 index 000000000000..567a378ffeea --- /dev/null +++ b/zh/api/Phalcon_Mvc_View.rst @@ -0,0 +1,336 @@ +Class **Phalcon\\Mvc\\View** +============================ + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +Phalcon\\Mvc\\View is a class for working with the "view" portion of the model-view-controller pattern. That is, it exists to help keep the view script separate from the model and controller scripts. It provides a system of helpers, output filters, and variable escaping. + +.. code-block:: php + + setViewsDir('app/views/'); + + $view->start(); + //Shows recent posts view (app/views/posts/recent.phtml) + $view->render('posts', 'recent'); + $view->finish(); + + //Printing views output + echo $view->getContent(); + + + +Constants +--------- + +*integer* **LEVEL_MAIN_LAYOUT** + +*integer* **LEVEL_AFTER_TEMPLATE** + +*integer* **LEVEL_LAYOUT** + +*integer* **LEVEL_BEFORE_TEMPLATE** + +*integer* **LEVEL_ACTION_VIEW** + +*integer* **LEVEL_NO_RENDER** + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Mvc\\View constructor + + + +public **setViewsDir** (*string* $viewsDir) + +Sets views directory. Depending of your platform, always add a trailing slash or backslash + + + +public *string* **getViewsDir** () + +Gets views directory + + + +public **setBasePath** (*string* $basePath) + +Sets base path. Depending of your platform, always add a trailing slash or backslash + +.. code-block:: php + + setBasePath(__DIR__.'/'); + + + + +public **setRenderLevel** (*string* $level) + +Sets the render level for the view + +.. code-block:: php + + view->setRenderLevel(Phalcon\Mvc\View::LEVEL_VIEW); + + + + +public **setMainView** (*unknown* $viewPath) + +Sets default view name. Must be a file without extension in the views directory + +.. code-block:: php + + view->setMainView('inicio'); + + + + +public **setTemplateBefore** (*string|array* $templateBefore) + +Appends template before controller layout + + + +public **cleanTemplateBefore** () + +Resets any template before layouts + + + +public **setTemplateAfter** (*string|array* $templateAfter) + +Appends template after controller layout + + + +public **cleanTemplateAfter** () + +Resets any template before layouts + + + +public **setParamToView** (*string* $key, *mixed* $value) + +Adds parameters to views (alias of setVar) + + + +public **setVar** (*string* $key, *mixed* $value) + +Adds parameters to views + + + +public *array* **getParamsToView** () + +Returns parameters to views + + + +public *string* **getControllerName** () + +Gets the name of the controller rendered + + + +public *string* **getActionName** () + +Gets the name of the action rendered + + + +public *array* **getParams** () + +Gets extra parameters of the action rendered + + + +public **start** () + +Starts rendering process enabling the output buffering + + + +protected *array* **_loadTemplateEngines** () + +Loads registered template engines, if none is registered it will use Phalcon\\Mvc\\View\\Engine\\Php + + + +protected **_engineRender** () + +Checks whether view exists on registered extensions and render it + + + +public **registerEngines** (*array* $engines) + +Register templating engines + +.. code-block:: php + + view->registerEngines(array( + ".phtml" => "Phalcon\Mvc\View\Engine\Php", + ".volt" => "Phalcon\Mvc\View\Engine\Volt", + ".mhtml" => "MyCustomEngine" + )); + + + + +public **render** (*string* $controllerName, *string* $actionName, *array* $params) + +Executes render process from dispatching data + +.. code-block:: php + + start(); + //Shows recent posts view (app/views/posts/recent.phtml) + $view->render('posts', 'recent'); + $view->finish(); + + + + +public **pick** (*string* $renderView) + +Choose a view different to render than last-controller/last-action + +.. code-block:: php + + view->pick("products/list"); + } + } + + + + +public *string* **partial** (*string* $partialPath) + +Renders a partial view + +.. code-block:: php + + partial('shared/footer'); + + + + +public **finish** () + +Finishes the render process by stopping the output buffering + + + +protected :doc:`Phalcon\\Cache\\Backend ` **_createCache** () + +Create a Phalcon\\Cache based on the internal cache options + + + +public :doc:`Phalcon\\Cache\\Backend ` **getCache** () + +Returns the cache instance used to cache + + + +public **cache** (*boolean|array* $options) + +Cache the actual view render to certain level + + + +public **setContent** (*string* $content) + +Externally sets the view content + +.. code-block:: php + + view->setContent("

hello

"); + + + + +public *string* **getContent** () + +Returns cached ouput from another view stage + + + +public *string* **getActiveRenderPath** () + +Returns the path of the view that is currently rendered + + + +public **disable** () + +Disable view. Don't show any view or template + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_View_Engine.rst b/zh/api/Phalcon_Mvc_View_Engine.rst new file mode 100755 index 000000000000..fc133ae8549c --- /dev/null +++ b/zh/api/Phalcon_Mvc_View_Engine.rst @@ -0,0 +1,59 @@ +Class **Phalcon\\Mvc\\View\\Engine** +==================================== + +*extends* :doc:`Phalcon\\DI\\Injectable ` + +All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\\Mvc\\View component. + + +Methods +--------- + +public **__construct** (:doc:`Phalcon\\Mvc\\View ` $view, :doc:`Phalcon\\DI ` $dependencyInjector) + +Phalcon\\Mvc\\View\\Engine constructor + + + +public *array* **getContent** () + +Returns cached ouput on another view stage + + + +public *string* **partial** (*string* $partialPath) + +Renders a partial inside another view + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_View_Engine_Php.rst b/zh/api/Phalcon_Mvc_View_Engine_Php.rst new file mode 100755 index 000000000000..965a62bdb34d --- /dev/null +++ b/zh/api/Phalcon_Mvc_View_Engine_Php.rst @@ -0,0 +1,65 @@ +Class **Phalcon\\Mvc\\View\\Engine\\Php** +========================================= + +*extends* :doc:`Phalcon\\Mvc\\View\\Engine ` + +Adapter to use PHP itself as templating engine + + +Methods +--------- + +public **render** (*string* $path, *array* $params, *bool* $mustClean) + +Renders a view using the template engine + + + +public **__construct** (:doc:`Phalcon\\Mvc\\View ` $view, :doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\Mvc\\View\\Engine + +Phalcon\\Mvc\\View\\Engine constructor + + + +public *array* **getContent** () inherited from Phalcon\\Mvc\\View\\Engine + +Returns cached ouput on another view stage + + + +public *string* **partial** (*string* $partialPath) inherited from Phalcon\\Mvc\\View\\Engine + +Renders a partial inside another view + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_View_Engine_Volt.rst b/zh/api/Phalcon_Mvc_View_Engine_Volt.rst new file mode 100644 index 000000000000..8b4844135064 --- /dev/null +++ b/zh/api/Phalcon_Mvc_View_Engine_Volt.rst @@ -0,0 +1,83 @@ +Class **Phalcon\\Mvc\\View\\Engine\\Volt** +========================================== + +*extends* :doc:`Phalcon\\Mvc\\View\\Engine ` + +Designer friendly and fast template engine for PHP written in C + + +Methods +--------- + +public **setOptions** (*array* $options) + +Set Volt's options + + + +public *array* **getOptions** () + +Return Volt's options + + + +public **render** (*string* $templatePath, *array* $params, *bool* $mustClean) + +Renders a view using the template engine + + + +public *int* **length** (*mixed* $item) + +Length filter + + + +public **__construct** (:doc:`Phalcon\\Mvc\\View ` $view, :doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\Mvc\\View\\Engine + +Phalcon\\Mvc\\View\\Engine constructor + + + +public *array* **getContent** () inherited from Phalcon\\Mvc\\View\\Engine + +Returns cached ouput on another view stage + + + +public *string* **partial** (*string* $partialPath) inherited from Phalcon\\Mvc\\View\\Engine + +Renders a partial inside another view + + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) inherited from Phalcon\\DI\\Injectable + +Sets the dependency injector + + + +public :doc:`Phalcon\\DI ` **getDI** () inherited from Phalcon\\DI\\Injectable + +Returns the internal dependency injector + + + +public **setEventsManager** (:doc:`Phalcon\\Events\\Manager ` $eventsManager) inherited from Phalcon\\DI\\Injectable + +Sets the event manager + + + +public :doc:`Phalcon\\Events\\Manager ` **getEventsManager** () inherited from Phalcon\\DI\\Injectable + +Returns the internal event manager + + + +public **__get** (*string* $propertyName) inherited from Phalcon\\DI\\Injectable + +Magic method __get + + + diff --git a/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst b/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst new file mode 100644 index 000000000000..0cb4a278f977 --- /dev/null +++ b/zh/api/Phalcon_Mvc_View_Engine_Volt_Compiler.rst @@ -0,0 +1,67 @@ +Class **Phalcon\\Mvc\\View\\Engine\\Volt\\Compiler** +==================================================== + +This class reads and compiles volt templates into PHP plain code + + +Methods +--------- + +public **setDI** (*unknown* $di) + +... + + +public **getDI** () + +... + + +protected **_functionCall** () + +Resolves function intermediate code into PHP function calls + + + +protected **_filter** () + +Resolves filter intermediate code into PHP function calls + + + +public **_expression** (*array* $expr, *bool* $extendsMode, *bool* $prependDollar) + +Resolves an expression node in an AST volt tree + + + +protected *string* **_statementList** () + +Traverses a statement list compiling each of its nodes + + + +protected *string* **_compileSource** () + +Compiles a Volt source code returning a PHP plain version + + + +public *string* **compileString** (*string* $viewCode, *boolean* $extendsMode) + +Compiles a template in a string + + + +public **compile** (*string* $path, *string* $compiledPath) + +Compiles a template into a file + + + +public *array* **parse** (*string* $viewCode) + +Parses a Volt template returning its intermediate representation + + + diff --git a/zh/api/Phalcon_Mvc_View_Exception.rst b/zh/api/Phalcon_Mvc_View_Exception.rst new file mode 100755 index 000000000000..66d3fddff47c --- /dev/null +++ b/zh/api/Phalcon_Mvc_View_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Mvc\\View\\Exception** +======================================= + +*extends* :doc:`Phalcon\\Exception ` + +Class for exceptions thrown by Phalcon\\Mvc\\View + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Paginator_Adapter_Model.rst b/zh/api/Phalcon_Paginator_Adapter_Model.rst new file mode 100755 index 000000000000..24a143236204 --- /dev/null +++ b/zh/api/Phalcon_Paginator_Adapter_Model.rst @@ -0,0 +1,27 @@ +Class **Phalcon\\Paginator\\Adapter\\Model** +============================================ + +This adapter allows to paginate data using Phalcon\\Model resultsets. + + +Methods +--------- + +public **__construct** (*array* $config) + +Phalcon\\Paginator\\Adapter\\Model constructor + + + +public **setCurrentPage** (*int* $page) + +Set the current page number + + + +public *stdClass* **getPaginate** () + +Returns a slice of the resultset to show in the pagination + + + diff --git a/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst b/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst new file mode 100644 index 000000000000..a051050ee17e --- /dev/null +++ b/zh/api/Phalcon_Paginator_Adapter_NativeArray.rst @@ -0,0 +1,27 @@ +Class **Phalcon\\Paginator\\Adapter\\NativeArray** +================================================== + +Component of pagination by array data + + +Methods +--------- + +public **__construct** (*array* $config) + +Phalcon\\Paginator\\Adapter\\NativeArray constructor + + + +public **setCurrentPage** (*int* $page) + +Set the current page number + + + +public *stdClass* **getPaginate** () + +Returns a slice of the resultset to show in the pagination + + + diff --git a/zh/api/Phalcon_Paginator_Exception.rst b/zh/api/Phalcon_Paginator_Exception.rst new file mode 100755 index 000000000000..73709b6fcd21 --- /dev/null +++ b/zh/api/Phalcon_Paginator_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Paginator\\Exception** +======================================= + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Paginator will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Session.rst b/zh/api/Phalcon_Session.rst new file mode 100755 index 000000000000..ea191378d9fa --- /dev/null +++ b/zh/api/Phalcon_Session.rst @@ -0,0 +1,90 @@ +Class **Phalcon\\Session** +========================== + +Session client-server persistent state data management. This component allows you to separate your session data between application or modules. With this, it's possible to use the same index to refer a variable but it can be in different applications. + +.. code-block:: php + + 'my-private-app' + )); + + $session->start(); + + $session->set('var', 'some-value'); + + echo $session->get('var'); + + + +Methods +--------- + +public **__construct** (*array* $options) + +Phalcon\\Session construtor + + + +public **start** () + +Starts session, optionally using an adapter + + + +public **setOptions** (*array* $options) + +Sets session options + + + +public *array* **getOptions** () + +Get internal options + + + +public **get** (*string* $index) + +Gets a session variable from an application context + + + +public **set** (*string* $index, *string* $value) + +Sets a session variable in an application context + + + +public **has** (*string* $index) + +Check whether a session variable is set in an application context + + + +public **remove** (*string* $index) + +Removes a session variable from an application context + + + +public *string* **getId** () + +Returns active session id + + + +public *boolean* **isStarted** () + +Check whether the session has been started + + + +public *boolean* **destroy** () + +Destroys the active session + + + diff --git a/zh/api/Phalcon_Session_Adapter_Files.rst b/zh/api/Phalcon_Session_Adapter_Files.rst new file mode 100644 index 000000000000..36cb4dcaaa08 --- /dev/null +++ b/zh/api/Phalcon_Session_Adapter_Files.rst @@ -0,0 +1,77 @@ +Class **Phalcon\\Session\\Adapter\\Files** +========================================== + +*extends* :doc:`Phalcon\\Session ` + +This adapter store sessions in plain files + + +Methods +--------- + +public **__construct** (*array* $options) inherited from Phalcon\\Session + +Phalcon\\Session construtor + + + +public **start** () inherited from Phalcon\\Session + +Starts session, optionally using an adapter + + + +public **setOptions** (*array* $options) inherited from Phalcon\\Session + +Sets session options + + + +public *array* **getOptions** () inherited from Phalcon\\Session + +Get internal options + + + +public **get** (*string* $index) inherited from Phalcon\\Session + +Gets a session variable from an application context + + + +public **set** (*string* $index, *string* $value) inherited from Phalcon\\Session + +Sets a session variable in an application context + + + +public **has** (*string* $index) inherited from Phalcon\\Session + +Check whether a session variable is set in an application context + + + +public **remove** (*string* $index) inherited from Phalcon\\Session + +Removes a session variable from an application context + + + +public *string* **getId** () inherited from Phalcon\\Session + +Returns active session id + + + +public *boolean* **isStarted** () inherited from Phalcon\\Session + +Check whether the session has been started + + + +public *boolean* **destroy** () inherited from Phalcon\\Session + +Destroys the active session + + + diff --git a/zh/api/Phalcon_Session_Bag.rst b/zh/api/Phalcon_Session_Bag.rst new file mode 100755 index 000000000000..ede15b92b18c --- /dev/null +++ b/zh/api/Phalcon_Session_Bag.rst @@ -0,0 +1,65 @@ +Class **Phalcon\\Session\\Bag** +=============================== + +This component helps to separate session data into "namespaces". Working by this way you can easily create groups of session variables into the application + +.. code-block:: php + + name = "Kimbra Johnson"; + $user->age = 22; + + + +Methods +--------- + +public **__construct** (*unknown* $name) + +... + + +public **setDI** (:doc:`Phalcon\\DI ` $dependencyInjector) + +Sets the DependencyInjector container + + + +public :doc:`Phalcon\\DI ` **getDI** () + +Returns the DependencyInjector container + + + +public **initialize** () + +Initializes the session bag. This method must not be called directly, the class calls it when its internal data is accesed + + + +public **destroy** () + +Destroyes the session bag + + + +public **__set** (*string* $property, *string* $value) + +Setter of values + + + +public *string* **__get** (*string* $property) + +Getter of values + + + +public *boolean* **__isset** (*string* $property) + +Isset property + + + diff --git a/zh/api/Phalcon_Session_Exception.rst b/zh/api/Phalcon_Session_Exception.rst new file mode 100644 index 000000000000..6662d133ed7f --- /dev/null +++ b/zh/api/Phalcon_Session_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Session\\Exception** +===================================== + +*extends* :doc:`Phalcon\\Exception ` + +Exceptions thrown in Phalcon\\Session will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Tag.rst b/zh/api/Phalcon_Tag.rst new file mode 100755 index 000000000000..ccd20f5e327f --- /dev/null +++ b/zh/api/Phalcon_Tag.rst @@ -0,0 +1,351 @@ +Class **Phalcon\\Tag** +====================== + +Phalcon\\Tag is designed to simplify building of HTML tags. It provides a set of helpers to generate HTML in a dynamic way. This component is an abstract class that you can extend to add more helpers. + + +Constants +--------- + +*integer* **HTML32** + +*integer* **HTML401_STRICT** + +*integer* **HTML401_TRANSITIONAL** + +*integer* **HTML401_FRAMESET** + +*integer* **HTML5** + +*integer* **XHTML10_STRICT** + +*integer* **XHTML10_TRANSITIONAL** + +*integer* **XHTML10_FRAMESET** + +*integer* **XHTML11** + +*integer* **XHTML20** + +*integer* **XHTML5** + +Methods +--------- + +public static **setDI** (*unknown* $dependencyInjector) + +Sets the dependency injector container. + + + +public static :doc:`Phalcon\\DI ` **getDI** () + +Internally gets the request dispatcher + + + +public static :doc:`Phalcon\\Mvc\\Url ` **getUrlService** () + +Return a URL service from the DI + + + +public static :doc:`Phalcon\\Mvc\\Dispatcher ` **getDispatcherService** () + +Returns a Dispatcher service from the DI + + + +public static **setDefault** (*string* $id, *string* $value) + +Assigns default values to generated tags by helpers + +.. code-block:: php + + 30)) + + + + +public static *string* **passwordField** (*array* $parameters) + +Builds a HTML input[type="password"] tag + +.. code-block:: php + + 30)) + + + + +public static *string* **hiddenField** (*array* $parameters) + +Builds a HTML input[type="hidden"] tag + +.. code-block:: php + + "mike")) + + + + +public static *string* **fileField** (*array* $parameters) + +Builds a HTML input[type="file"] tag + +.. code-block:: php + + 30)) + + + + +public static *string* **radioField** (*array* $parameters) + +Builds a HTML input[type="radio"] tag + +.. code-block:: php + + 30)) + + + + +public static *string* **submitButton** (*unknown* $parameters) + +Builds a HTML input[type="submit"] tag + +.. code-block:: php + + "Active", "I" => "Inactive")) + + + + +public static *string* **select** (*unknown* $parameters, *unknown* $data) + +Builds a HTML SELECT tag using a Phalcon_Model resultset as options + +.. code-block:: php + + array("id", "name") + )); + + + + +public static *string* **textArea** (*array* $parameters) + +Builds a HTML TEXTAREA tag + +.. code-block:: php + + 10, "rows" => 4)) + + + + +public static *string* **form** (*array* $parameters) + +Builds a HTML FORM tag + +.. code-block:: php + + "post")); + + + + +public static *string* **endForm** () + +Builds a HTML close FORM tag + + + +public static **setTitle** (*string* $title) + +Set the title of view content + + + +public static **appendTitle** (*string* $title) + +Add to title of view content + + + +public static **prependTitle** (*string* $title) + +Add before the title of view content + + + +public static *string* **getTitle** () + +Get the title of view content + + + +public static *string* **stylesheetLink** (*array* $parameters, *boolean* $local) + +Builds a LINK[rel="stylesheet"] tag + +.. code-block:: php + + ` + +Exceptions thrown in Phalcon\\Tag will use this class + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Tag_Select.rst b/zh/api/Phalcon_Tag_Select.rst new file mode 100755 index 000000000000..ed5a1ee78fef --- /dev/null +++ b/zh/api/Phalcon_Tag_Select.rst @@ -0,0 +1,25 @@ +Class **Phalcon\\Tag\\Select** +============================== + +Generates a SELECT html tag using an static array of values or a Phalcon\\Model resultset + + +Methods +--------- + +public static **selectField** (*array* $parameters, *array* $data) + +Generates a SELECT tag + + + +protected static **_optionsFromResultset** () + +... + + +protected static **_optionsFromArray** () + +... + + diff --git a/zh/api/Phalcon_Text.rst b/zh/api/Phalcon_Text.rst new file mode 100755 index 000000000000..ad27d58f8d92 --- /dev/null +++ b/zh/api/Phalcon_Text.rst @@ -0,0 +1,40 @@ +Class **Phalcon\\Text** +======================= + +Provides utilities when working with strings + + +Methods +--------- + +public static *string* **camelize** (*string* $str) + +Converts strings to camelize style + +.. code-block:: php + + ` + +*implements* ArrayAccess + +Allows to define translation lists using PHP arrays + + +Methods +--------- + +public **__construct** (*unknown* $options) + +Phalcon\\Translate\\Adapter\\NativeArray constructor + + + +public *string* **query** (*string* $index, *array* $placeholders) + +Returns the translation related to the given key + + + +public *bool* **exists** (*string* $index) + +Check whether is defined a translation key in the internal array + + + +public *string* **_** (*string* $translateKey, *array* $placeholders) inherited from Phalcon\\Translate + +Returns the translation string of the given key + + + +public **offsetSet** (*string* $offset, *string* $value) inherited from Phalcon\\Translate + +Sets a translation value + + + +public *boolean* **offsetExists** (*string* $translateKey) inherited from Phalcon\\Translate + +Check whether a translation key exists + + + +public **offsetUnset** (*string* $offset) inherited from Phalcon\\Translate + +Elimina un indice del diccionario + + + +public *string* **offsetGet** (*string* $traslateKey) inherited from Phalcon\\Translate + +Returns the translation related to the given key + + + diff --git a/zh/api/Phalcon_Translate_Exception.rst b/zh/api/Phalcon_Translate_Exception.rst new file mode 100755 index 000000000000..ccd4d7246fb2 --- /dev/null +++ b/zh/api/Phalcon_Translate_Exception.rst @@ -0,0 +1,71 @@ +Class **Phalcon\\Translate\\Exception** +======================================= + +*extends* :doc:`Phalcon\\Exception ` + +Class for exceptions thrown by Phalcon\\Translate + + +Methods +--------- + +final private *Exception* **__clone** () inherited from Exception + +Clone the exception + + + +public **__construct** (*string* $message, *int* $code, *Exception* $previous) inherited from Exception + +Exception constructor + + + +final public *string* **getMessage** () inherited from Exception + +Gets the Exception message + + + +final public *int* **getCode** () inherited from Exception + +Gets the Exception code + + + +final public *string* **getFile** () inherited from Exception + +Gets the file in which the exception occurred + + + +final public *int* **getLine** () inherited from Exception + +Gets the line in which the exception occurred + + + +final public *array* **getTrace** () inherited from Exception + +Gets the stack trace + + + +final public *Exception* **getPrevious** () inherited from Exception + +Returns previous Exception + + + +final public *Exception* **getTraceAsString** () inherited from Exception + +Gets the stack trace as a string + + + +public *string* **__toString** () inherited from Exception + +String representation of the exception + + + diff --git a/zh/api/Phalcon_Version.rst b/zh/api/Phalcon_Version.rst new file mode 100644 index 000000000000..e4af26c4202e --- /dev/null +++ b/zh/api/Phalcon_Version.rst @@ -0,0 +1,27 @@ +Class **Phalcon\\Version** +========================== + +This version allows to get version of the framework + + +Methods +--------- + +protected static **_getVersion** () + +Area where the version number is set. The format is as follows: ABBCCDE A - Major version B - Med version (two digits) C - Min version (two digits) D - Special release: 1 = Alpha, 2 = Beta, 3 = RC, 4 = Stable E - Special release version i.e. RC1, Beta2 etc. + + + +public static *string* **get** () + +Returns the active version (string) + + + +public static *int* **getId** () + +Returns the numeric active version + + + diff --git a/zh/api/index.rst b/zh/api/index.rst new file mode 100755 index 000000000000..8372259211ea --- /dev/null +++ b/zh/api/index.rst @@ -0,0 +1,147 @@ +API Indice +----------------- + +.. toctree:: + :maxdepth: 1 + + Phalcon_Acl + Phalcon_Acl_Adapter_Memory + Phalcon_Acl_Exception + Phalcon_Acl_Resource + Phalcon_Acl_Role + Phalcon_CLI_Console + Phalcon_CLI_Console_Exception + Phalcon_CLI_Dispatcher + Phalcon_CLI_Dispatcher_Exception + Phalcon_CLI_Router + Phalcon_CLI_Router_Exception + Phalcon_CLI_Task + Phalcon_Cache_Backend + Phalcon_Cache_Backend_Apc + Phalcon_Cache_Backend_File + Phalcon_Cache_Backend_Memcache + Phalcon_Cache_Backend_Mongo + Phalcon_Cache_Exception + Phalcon_Cache_Frontend_Base64 + Phalcon_Cache_Frontend_Data + Phalcon_Cache_Frontend_None + Phalcon_Cache_Frontend_Output + Phalcon_Config + Phalcon_Config_Adapter_Ini + Phalcon_Config_Exception + Phalcon_DI + Phalcon_DI_Exception + Phalcon_DI_FactoryDefault + Phalcon_DI_FactoryDefault_CLI + Phalcon_DI_Injectable + Phalcon_Db + Phalcon_Db_Adapter_Pdo + Phalcon_Db_Adapter_Pdo_Mysql + Phalcon_Db_Adapter_Pdo_Postgresql + Phalcon_Db_Adapter_Pdo_Sqlite + Phalcon_Db_Column + Phalcon_Db_Dialect + Phalcon_Db_Dialect_Mysql + Phalcon_Db_Dialect_Postgresql + Phalcon_Db_Dialect_Sqlite + Phalcon_Db_Exception + Phalcon_Db_Index + Phalcon_Db_Profiler + Phalcon_Db_Profiler_Item + Phalcon_Db_RawValue + Phalcon_Db_Reference + Phalcon_Db_Result_Pdo + Phalcon_Dispatcher + Phalcon_Escaper + Phalcon_Escaper_Exception + Phalcon_Events_Event + Phalcon_Events_Exception + Phalcon_Events_Manager + Phalcon_Exception + Phalcon_Filter + Phalcon_Filter_Exception + Phalcon_Flash + Phalcon_Flash_Direct + Phalcon_Flash_Exception + Phalcon_Flash_Session + Phalcon_Http_Request + Phalcon_Http_Request_Exception + Phalcon_Http_Request_File + Phalcon_Http_Response + Phalcon_Http_Response_Exception + Phalcon_Http_Response_Headers + Phalcon_Loader + Phalcon_Loader_Exception + Phalcon_Logger + Phalcon_Logger_Adapter_File + Phalcon_Logger_Exception + Phalcon_Logger_Item + Phalcon_Mvc_Application + Phalcon_Mvc_Application_Exception + Phalcon_Mvc_Collection + Phalcon_Mvc_Collection_Exception + Phalcon_Mvc_Collection_Manager + Phalcon_Mvc_Controller + Phalcon_Mvc_Dispatcher + Phalcon_Mvc_Dispatcher_Exception + Phalcon_Mvc_Micro + Phalcon_Mvc_Micro_Exception + Phalcon_Mvc_Model + Phalcon_Mvc_Model_Criteria + Phalcon_Mvc_Model_Exception + Phalcon_Mvc_Model_Manager + Phalcon_Mvc_Model_Message + Phalcon_Mvc_Model_MetaData + Phalcon_Mvc_Model_MetaData_Apc + Phalcon_Mvc_Model_MetaData_Files + Phalcon_Mvc_Model_MetaData_Memory + Phalcon_Mvc_Model_MetaData_Session + Phalcon_Mvc_Model_Query + Phalcon_Mvc_Model_Query_Lang + Phalcon_Mvc_Model_Query_Status + Phalcon_Mvc_Model_Resultset + Phalcon_Mvc_Model_Resultset_Complex + Phalcon_Mvc_Model_Resultset_Simple + Phalcon_Mvc_Model_Row + Phalcon_Mvc_Model_Transaction + Phalcon_Mvc_Model_Transaction_Exception + Phalcon_Mvc_Model_Transaction_Failed + Phalcon_Mvc_Model_Transaction_Manager + Phalcon_Mvc_Model_Validator + Phalcon_Mvc_Model_Validator_Email + Phalcon_Mvc_Model_Validator_Exclusionin + Phalcon_Mvc_Model_Validator_Inclusionin + Phalcon_Mvc_Model_Validator_Numericality + Phalcon_Mvc_Model_Validator_PresenceOf + Phalcon_Mvc_Model_Validator_Regex + Phalcon_Mvc_Model_Validator_StringLength + Phalcon_Mvc_Model_Validator_Uniqueness + Phalcon_Mvc_Router + Phalcon_Mvc_Router_Exception + Phalcon_Mvc_Router_Route + Phalcon_Mvc_Url + Phalcon_Mvc_Url_Exception + Phalcon_Mvc_User_Component + Phalcon_Mvc_User_Module + Phalcon_Mvc_User_Plugin + Phalcon_Mvc_View + Phalcon_Mvc_View_Engine + Phalcon_Mvc_View_Engine_Php + Phalcon_Mvc_View_Engine_Volt + Phalcon_Mvc_View_Engine_Volt_Compiler + Phalcon_Mvc_View_Exception + Phalcon_Paginator_Adapter_Model + Phalcon_Paginator_Adapter_NativeArray + Phalcon_Paginator_Exception + Phalcon_Session + Phalcon_Session_Adapter_Files + Phalcon_Session_Bag + Phalcon_Session_Exception + Phalcon_Tag + Phalcon_Tag_Exception + Phalcon_Tag_Select + Phalcon_Text + Phalcon_Translate + Phalcon_Translate_Adapter_NativeArray + Phalcon_Translate_Exception + Phalcon_Version diff --git a/zh/conf.py b/zh/conf.py new file mode 100755 index 000000000000..bd638cfb04f1 --- /dev/null +++ b/zh/conf.py @@ -0,0 +1,244 @@ +# -*- coding: utf-8 -*- +# +# Phalcon PHP Framework Documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 10 12:27:41 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'Phalcon' +copyright = '2012, Phalcon Team' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.6.x' + +# The full version, including alpha/beta/rc tags. +release = '0.6.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None +language = 'zh' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'phalcon' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +html_theme_path = ['_theme'] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = "v documentation" + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +html_favicon = 'en/_static/favicon.ico' + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['../en/_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +html_domain_indices = True + +# If false, no index is generated. +html_use_index = True + +# If true, the index is split into individual pages for each letter. +html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'PhalconDocumentationdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'PhalconDocumentation.tex', 'Phalcon PHP Framework Documentation', + 'Phalcon Team', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'phalcondocumentation', 'Phalcon PHP Framework Documentation', + ['Phalcon Team'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'PhalconDocumentation', 'Phalcon PHP Framework Documentation', + 'Phalcon Team', 'PhalconDocumentation', 'PhalconPHP is a web framework delivered as a C extension providing high performance and lower resource consumption.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/zh/index.rst b/zh/index.rst new file mode 100755 index 000000000000..963ec56c208a --- /dev/null +++ b/zh/index.rst @@ -0,0 +1,88 @@ +Welcome! +======== + +欢迎使用Phalcon php 框架,我们的使命是给你一个开发网站及应用的高级工具,而你却不必担心性能问题. + +什么是 Phalcon? +------------------ + +Phalcon 是一个开源的,全堆栈的,用C语言写成的php5框架,专为高性能设计。你不需要学习和使用C语言的功能,因为这是一个PHP框架,只不过用C写成而已。同时Phalcon是松耦合的,您可以根据需要使用其他组件。 + +Phalcon不只是性能优越,我们的目标是让它强大而且易于使用! + +译者说明 +---------------------- +一般都是直接看英文资料,大都能看得懂。但看到Phalcon框架如此优秀,在学习后就想和大家分享,但发现国内的人几乎没有使用的,故想翻译一下,一旦翻译才发现读懂和译出一篇好文章真的不太一样。 +故前一期翻译的部分章节有点生硬,等有空的时候再回头重译吧,后面的一部分也是以英文文档为基础,但并不再是逐句翻译了。 + +09年左右,大量的框架出现,我看过的框架不下20种,最先看到的可能就是php.MVC了,这是一个按照struts 1x编写的,只不过同时加载的类库太多了,效率不高而且不太完善。 + +后来稍有名的包括 cakephp, Symfony, Akelos, Prado, Kohana等,最近几年流行的就是 zf, yii, ci等,当然还有国内几个比较有名的框架,如fleaphp, thinkphp等。 + +在上面的一些框架中,我比较感冒的还是ci,yii,thinkphp等。ci,thinkphp够简单,速度也不错。yii是生活在国外的华人开发,功能够全而强大,速度也不错,国内的应用也不少。 + +一直不太喜欢zf,记得几年前就和同行朋友聊天的时候说,像ZEND公司完全可以用C语言开发出一个扩展来,这样效率会高得多,为毛非得用PHP开发呢,事实被我验证了,但开发扩展的不是ZEND公司,而是国内一个PHP大鸟,人称鸟哥。这个框架就是非常出名的YAF,因此YAF扩展是我必装的扩展之一。同时这也是我发现的第一个C语言写的扩展框架。 + +但YAF的缺点是,功能非常不完善,在我看来只是简单实现了MVC结构及路由,分发等功能,像一些ORM之类的功能完全没有开发,作者好像也没有开发的意思:) + +后来就发现了Phalcon,一看文档就爱上了她,功能,速度等都是我想要的,我花了一周时间看文档学习她,并在一个下午的过程中,发现了文档中的三个错误并提交了这些错误:),我决定为完善它也贡献一点自己的力量。 + +本文档的中文地址存放在 http://phalcon.5iunix.net + +Github上的地址为: https://github.com/netstu/phalcondocs ,您如果发现有些地方译的有些操蛋,烦请你clone它,并完善她。 + +目录 +------------- + +.. toctree:: + :maxdepth: 2 + + reference/motivation + reference/benchmark + reference/install + reference/tutorial + reference/tutorial-invo + reference/tutorial-rest + reference/di + reference/mvc + reference/controllers + reference/models + reference/phql + reference/odm + reference/views + reference/tags + reference/volt + reference/applications + reference/routing + reference/dispatching + reference/micro + reference/namespaces + reference/events + reference/request + reference/response + reference/url + reference/flash + reference/session + reference/filter + reference/config + reference/pagination + reference/cache + reference/acl + reference/translate + reference/loader + reference/logging + reference/cli + reference/db + reference/intl + reference/migrations + reference/debug + reference/tools + api/index + reference/license + +其他格式 +--------------- + +* `PDF `_ +* `HTML in one Zip `_ +* `ePub `_ \ No newline at end of file diff --git a/zh/make.bat b/zh/make.bat new file mode 100755 index 000000000000..36563b43711c --- /dev/null +++ b/zh/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PhalconDocumentation.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PhalconDocumentation.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/zh/reference/acl.rst b/zh/reference/acl.rst new file mode 100755 index 000000000000..9e52a13775f9 --- /dev/null +++ b/zh/reference/acl.rst @@ -0,0 +1,176 @@ +Access Control Lists ACL +======================== +:doc:`Phalcon\\Acl <../api/Phalcon_Acl>` provides an easy and lightweight management of ACLs as well as the permissions attached to them. `Access Control Lists`_ (ACL) allow an application to control access to its areas and the underlying objects from requests. You are encouraged to read more about the ACL methodology so as to be familiar with its concepts. + +In summary, ACLs have roles and resources. Resources are objects which abide by the permissions defined to them by the ACLs. Roles are objects that request access to resources and can be allowed or denied access by the ACL mechanism. + +Creating an ACL +--------------- +This component is designed to initially work in memory. This provides ease of use and speed in accessing every aspect of the list. The :doc:`Phalcon\\Acl <../api/Phalcon_Acl>` constructor takes as its first parameter an adapter used to retriever the information related to the control list. An example using the memory adapter is below: + +.. code-block:: php + + ` allows access to action on resources that have not been yet defined. To increase the security level of the access list we can define a "deny" level as a default access level. + +.. code-block:: php + + setDefaultAction(Phalcon\Acl::DENY); + +Adding Roles to the ACL +----------------------- +A role is an object that can or cannot access certain resources in the access list. As an example, we will define roles as groups of people in an organization. The :doc:`Phalcon\\Acl\\Role <../api/Phalcon_Acl_Role>` class is available to create roles in a more structured way. Let's add some roles to our recently created list: + +.. code-block:: php + + addRole($roleGuests); + + // Add "Designers" role to acl without a Phalcon\Acl\Role + $acl->addRole("Designers"); + +As you can see, roles are defined directly without using a instance. + +Adding Resources +---------------- +Resources are objects where access is controlled. Normally in MVC applications resources refer to controllers. Although this is not mandatory, the :doc:`Phalcon\\Acl\\Resource <../api/Phalcon_Acl_Resource>` class can be used in defining resources. It's important to add related actions or operations to a resource so that the ACL can understand what it should to control. + +.. code-block:: php + + addResource($customersResource, "search"); + $acl->addResource($customersResource, array("create", "update")); + +Defining Access Controls +------------------------ +Now we've roles and resources. It's time to define the ACL i.e. which roles can access which resources. This part is very important especially taking in consideration your default access level "allow" or "deny". + +.. code-block:: php + + allow("Guests", "Customers", "search"); + $acl->allow("Guests", "Customers", "create"); + $acl->deny("Guests", "Customers", "update"); + +The allow method designates that a particular role has granted access to access a particular resource. The deny method does the opposite. + +Querying an ACL +--------------- +Once the list has been completely defined. We can query it to check if a role has a given permission or not. + +.. code-block:: php + + isAllowed("Guests", "Customers", "edit"); //Returns 0 + $acl->isAllowed("Guests", "Customers", "search"); //Returns 1 + $acl->isAllowed("Guests", "Customers", "create"); //Returns 1 + +Roles Inheritance +----------------- +You can build complex role structures using the inheritance that :doc:`Phalcon\\Acl\\Role <../api/Phalcon_Acl_Role>` provides. Roles can inherit from other roles, thus allowing access to supersets or subsets of resources. To use role inheritance, you need to pass the inherited role as the second parameter of the function call, when adding that role in the list. + +.. code-block:: php + + addRole($roleGuests); + + // Add "Administrators" role inheriting from "Guests" its accesses + $acl->addRole($roleAdmins, $roleGuests); + +Serializing ACL lists +--------------------- +To improve performance :doc:`Phalcon\\Acl <../api/Phalcon_Acl>` instances can be serialized and stored in text files or a database table so that they can be loaded at will without having to redefine the whole list. You can do that as follows: + +.. code-block:: php + + isAllowed("Guests", "Customers", "edit")) { + echo "Access granted!"; + } else { + echo "Access denied :("; + } + +Acl Events +---------- +:doc:`Phalcon\\Acl <../api/Phalcon_Acl>` is able to send events to a :doc:`EventsManager ` if it's present. Events +are triggered using the type "acl". Some events when returning boolean false could stop the active operation. The following events are supported: + ++----------------------+------------------------------------------------------------+---------------------+ +| Event Name | Triggered | Can stop operation? | ++======================+============================================================+=====================+ +| beforeCheckAccess | Triggered before check if a role/resource has access | Yes | ++----------------------+------------------------------------------------------------+---------------------+ +| afterCheckAccess | Triggered after check if a role/resource has access | No | ++----------------------+------------------------------------------------------------+---------------------+ + +The following example demonstrates how to attach listeners to this component: + +.. code-block:: php + + attach("acl", function($event, $acl) { + if ($event->getType() == 'beforeCheckAccess') { + echo $acl->getActiveRole(), + $acl->getActiveResource(), + $acl->getActiveAccess(); + } + }); + + $acl = new \Phalcon\Acl\Adapter\Memory(); + + //Setup the $acl + //... + + //Bind the eventsManager to the acl component + $acl->setEventsManager($eventManagers); + + +.. _Access Control Lists: http://en.wikipedia.org/wiki/Access_control_list diff --git a/zh/reference/applications.rst b/zh/reference/applications.rst new file mode 100644 index 000000000000..6f1f789ed2dd --- /dev/null +++ b/zh/reference/applications.rst @@ -0,0 +1,374 @@ +MVC Applications +================ +All the hard work behind orchestrating the operation of MVC in Phalcon is normally done by +:doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>`. This component encapsulates all the complex +operations required in the background, instantiating every component needed and integrating it with the +project, to allow the MVC pattern to operate as desired. + +Single or Multi Module Applications +----------------------------------- +With this component you can run various types of MVC structures: + +Single Module +^^^^^^^^^^^^^ +Single MVC applications consist of one module only. Namespaces can be used but are not necessary. +An application like this would have the following file structure: + +.. code-block:: php + + single/ + app/ + controllers/ + models/ + views/ + public/ + css/ + img/ + js/ + +If namespaces are not used, the following bootstrap file could be used to orchestrate the MVC flow: + +.. code-block:: php + + registerDirs( + array( + '../apps/controllers/', + '../apps/models/' + ) + )->register(); + + $di = new \Phalcon\DI\FactoryDefault(); + + // Registering the view component + $di->set('view', function() { + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir('../apps/views/'); + return $view; + }); + + try { + $application = new \Phalcon\Mvc\Application(); + $application->setDI($di); + echo $application->handle()->getContent(); + } catch(Phalcon\Exception $e) { + echo $e->getMessage(); + } + +If namespaces are used, the following bootstrap can be used: + +.. code-block:: php + + registerNamespaces( + array( + 'Single\Controllers' => '../apps/controllers/', + 'Single\Models' => '../apps/models/', + ) + )->register(); + + $di = new \Phalcon\DI\FactoryDefault(); + + // Register the dispatcher setting a Namespace for controllers + // Pay special attention to the double slashes at the end of the + // parameter used in the setDefaultNamespace function + $di->set('dispatcher', function() { + $dispatcher = new \Phalcon\Mvc\Dispatcher(); + $dispatcher->setDefaultNamespace('Single\Controllers\\'); + return $dispatcher; + }); + + // Registering the view component + $di->set('view', function() { + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir('../apps/views/'); + return $view; + }); + + try { + $application = new \Phalcon\Mvc\Application(); + $application->setDI($di); + echo $application->handle()->getContent(); + } catch(Phalcon\Exception $e){ + echo $e->getMessage(); + } + + +Multi Module +^^^^^^^^^^^^ +A multi-module application uses the same document root for more than one module. In this case the following file structure can be used: + +.. code-block:: php + + multiple/ + apps/ + frontend/ + controllers/ + models/ + views/ + Module.php + backend/ + controllers/ + models/ + views/ + Module.php + public/ + css/ + img/ + js/ + +Each directory in apps/ have its own MVC structure. A Module.php is present to configure specific settings of each module like autoloaders or custom services: + +.. code-block:: php + + registerNamespaces( + array( + 'Multiple\Backend\Controllers' => '../apps/backend/controllers/', + 'Multiple\Backend\Models' => '../apps/backend/models/', + ) + ); + + $loader->register(); + } + + /** + * Register specific services for the module + */ + public function registerServices($di) + { + + //Registering a dispatcher + $di->set('dispatcher', function() { + $dispatcher = new \Phalcon\Mvc\Dispatcher(); + $dispatcher->setDefaultNamespace("Multiple\Backend\Controllers\\"); + return $dispatcher; + }); + + //Registering the view component + $di->set('view', function() { + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir('../apps/backend/views/'); + return $view; + }); + } + + } + +A special bootstrap file is required to load the a multi-module MVC architecture: + +.. code-block:: php + + set('router', function () { + + $router = new \Phalcon\Mvc\Router(); + + $router->setDefaultModule("frontend"); + + $router->add( + "/login", + array( + 'module' => 'backend', + 'controller' => 'login', + 'action' => 'index', + ) + ); + + $router->add( + "/admin/products/:action", + array( + 'module' => 'backend', + 'controller' => 'products', + 'action' => 1, + ) + ); + + $router->add( + "/products/:action", + array( + 'module' => 'frontend', + 'controller' => 'products', + 'action' => 1, + ) + ); + + return $router; + + }); + + try { + + //Create an application + $application = new \Phalcon\Mvc\Application(); + $application->setDI($di); + + // Register the installed modules + $application->registerModules( + array( + 'frontend' => array( + 'className' => 'Multiple\Frontend\Module', + 'path' => '../apps/frontend/Module.php', + ), + 'backend' => array( + 'className' => 'Multiple\Backend\Module', + 'path' => '../apps/backend/Module.php', + ) + ) + ); + + //Handle the request + echo $application->handle()->getContent(); + + } catch(Phalcon\Exception $e){ + echo $e->getMessage(); + } + +When :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>` have modules registered, always is +necessary that every matched route returns a valid module. Each registered module has an associated class +that offers functions to set the module itself up. Each module class definition must implement two +methods: registerAutoloaders() and registerServices(), they will be called by +:doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>` according to the module to be executed. + +Understanding the default behavior +---------------------------------- +If you've been following the :doc:`tutorial ` or have generated the code using :doc:`Phalcon Devtools `, +you may recognize the following bootstrap file: + +.. code-block:: php + + setDI($di); + echo $application->handle()->getContent(); + + } catch (\Phalcon\Exception $e) { + echo "PhalconException: ", $e->getMessage(); + } + +The core of all the work of the controller occurs when handle() is invoked: + +.. code-block:: php + + handle()->getContent(); + +If you do not wish to use :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>`, the code above can be changed as follows: + +.. code-block:: php + + getShared('router'); + $router->handle(); + + $view = $di->getShared('view'); + + $dispatcher = $di->getShared('dispatcher'); + + // Pass the proccessed router parameters to the dispatcher + $dispatcher->setControllerName($router->getControllerName()); + $dispatcher->setActionName($router->getActionName()); + $dispatcher->setParams($router->getParams()); + + // Start the view + $view->start(); + + // Dispatch the request + $dispatcher->dispatch(); + + // Render the related views + $view->render( + $dispatcher->getControllerName(), + $dispatcher->getActionName(), + $dispatcher->getParams() + ); + + // Finish the view + $view->finish(); + + $response = $di->getShared('response'); + + // Pass the output of the view to the response + $response->setContent($view->getContent()); + + // Send the request headers + $response->sendHeaders(); + + // Print the response + echo $response->getContent(); + +Although the above is a lot more verbose than the code needed while using :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>`, +it offers an alternative in boostraping your application. Depending on your needs, you might want to have full control of what +should be instantiated or not, or replace certain components with those of your own to extend the default functionality. + +Application Events +------------------ +:doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>` is able to send events to the :doc:`EventsManager ` +(if it is present). Events are triggered using the type "application". The following events are supported: + ++---------------------+--------------------------------------------------------------+ +| Event Name | Triggered | ++=====================+==============================================================+ +| beforeStartModule | Before initialize a module, only when modules are registered | ++---------------------+--------------------------------------------------------------+ +| afterStartModule | After initialize a module, only when modules are registered | ++---------------------+--------------------------------------------------------------+ +| beforeHandleRequest | Before execute the dispatch loop | ++---------------------+--------------------------------------------------------------+ +| afterHandleRequest | After execute the dispatch loop | ++---------------------+--------------------------------------------------------------+ + +The following example demonstrates how to attach listeners to this component: + +.. code-block:: php + + setEventsManager($eventsManager); + + $eventsManager->attach( + "application", + function($event, $application) { + // ... + } + ); diff --git a/zh/reference/benchmark.rst b/zh/reference/benchmark.rst new file mode 100755 index 000000000000..7e152cba40e5 --- /dev/null +++ b/zh/reference/benchmark.rst @@ -0,0 +1,65 @@ +框架基准测试 +================= + +在过去,开发的web应用程序,性能问题并不是作为首要考虑的问题之一。因为硬件可以填补这方面的不足。然后,当Google决定把网站的速度作为搜索排名的条件之一时,性能的重要性就体现出来了。 + +以下的基准测试,将展示Phalcon和其他传统的PHP框架的性能对比,这些基准框架的版本都是最新的稳定版本。 + +我们欢迎程序员利用我们的基准测试程序进行测试,如果您有更好的优化方案或意见,请 `write us`_. `Check out source at Github`_ + +测试的环境? +------------------- +所有的框架都开启了 APC_ 缓存,且禁用了apache mod_rewrite模块,以避免产生额外的性能开销. + +下面是测试的硬件环境: + +* Operating System: Mac OS X Lion 10.7.4 +* Web Server: Apache httpd 2.2.22 +* PHP: 5.3.15 +* CPU: 2.04 Ghz Intel Core i5 +* Main Memory: 4GB 1333 MHz DDR3 +* Hard Drive: 500GB SATA Disk + +*PHP version and info:* + +.. figure:: ../_static/img/bench-4.png + :align: center + +*APC settings:* + +.. figure:: ../_static/img/bench-5.png + :align: center + + +List of Benchmarks +------------------ + +.. toctree:: + :maxdepth: 1 + + benchmark/hello-world + benchmark/micro + +ChangeLog +--------- + +.. versionadded:: 1.0 + Update Mar-20-2012: Benchmarks redone changing the apc.stat setting to Off. More Info + +.. versionchanged:: 1.1 + Update May-13-2012: Benchmarks redone PHP plain templating engine instead of Twig for Symfony. Configuration settings for Yii were also changed as recommended. + +.. versionchanged:: 1.2 + Update May-20-2012: Fuel framework was added to benchmarks. + +.. versionchanged:: 1.3 + Update Jun-4-2012: Cake framework was added to benchmarks. It is not however present in the graphics, since it takes 30 seconds to run only 10 of 1000. + +.. versionchanged:: 1.4 + Update Ago-27-2012: PHP updated to 5.3.15, APC updated to 3.1.11, Yii updated to 1.1.12, Phalcon updated to 0.5.0, Added Laravel, OS updated to Mac OS X Lion. Hardware upgraded. + +.. _decided: http://googlewebmastercentral.blogspot.com/2010/04/using-site-speed-in-web-search-ranking.html +.. _write us: http://phalcon.uservoice.com/ +.. _Check out source at Github: https://github.com/phalcon/framework-bench +.. _APC: http://php.net/manual/en/book.apc.php + diff --git a/zh/reference/benchmark/hello-world.rst b/zh/reference/benchmark/hello-world.rst new file mode 100644 index 000000000000..2615b43f1857 --- /dev/null +++ b/zh/reference/benchmark/hello-world.rst @@ -0,0 +1,684 @@ +Hello World Benchmark +===================== + +How the benchmarks were performed? +---------------------------------- + +We created a "Hello World" benchmark seeking to identify the smallest load overhead of each framework. Many people don't like this kind of benchmark because real-world applications require more complex features or structures. However, these tests identify the minimum time spent by each framework to perform a simple task. Such a task represents the mimimum requirement for every framework to process a single request. + +More specifically, the benchmark only measures the time it takes for a framework to start, run an action and free up resources at the end of the request. Any PHP application based on an MVC architecture will require this time. Due to the simplicity of the benchmark, we ensure that the time needed for a more complex request will be higher. + +A controller and a view have been created for each framework. The controller "say" and action "hello". The action only sends data to the view which displays it ("Hello!"). Using the "ab" benchmark tool we sent 1000 requests using 5 concurrent connections to each framework. + +What measurements were recorded? +-------------------------------- +These were the measurements we record to identify the overall performance of each framework: + +* Requests per second +* Time across all concurrent requests +* Number of included PHP files on a single request (measured using function get_included_files_. +* Memory Usage per request (measured using function memory_get_usage_. + +Pariticipant Frameworks +----------------------- + +* Yii_ (YII_DEBUG=false) (yii-1.1.12.b600af) +* Symfony_ (2.0.11) +* `Zend Framework`_ (1.11.11) +* Kohana_ (3.2.0) +* FuelPHP_ (1.2.1) +* CakePHP_ (2.1.3) +* Laravel_ 3.2.5 +* CodeIgniter_ (2.1.0) +* Nette_ (2.0.4) + +Results +------- + +Yii (YII_DEBUG=false) Version yii-1.1.12.b600af +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/yii/index.php?r=say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/yii/index.php?r=say/hello + Document Length: 61 bytes + + Concurrency Level: 5 + Time taken for tests: 1.174 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 254000 bytes + HTML transferred: 61000 bytes + Requests per second: 851.83 [#/sec] (mean) + Time per request: 5.870 [ms] (mean) + Time per request: 1.174 [ms] (mean, across all concurrent requests) + Transfer rate: 211.29 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 6 2.5 5 20 + Processing: 0 0 0.4 0 6 + Waiting: 0 0 0.3 0 6 + Total: 2 6 2.5 5 20 + + Percentage of the requests served within a certain time (ms) + 50% 5 + 66% 6 + 75% 7 + 80% 7 + 90% 9 + 95% 11 + 98% 14 + 99% 15 + 100% 20 (longest request) + +Symfony Version 2.0.11 +^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/Symfony/web/app.php/say/hello/ + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/Symfony/web/app.php/say/hello/ + Document Length: 16 bytes + + Concurrency Level: 5 + Time taken for tests: 1.848 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 249000 bytes + HTML transferred: 16000 bytes + Requests per second: 541.01 [#/sec] (mean) + Time per request: 9.242 [ms] (mean) + Time per request: 1.848 [ms] (mean, across all concurrent requests) + Transfer rate: 131.55 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 9 4.8 8 61 + Processing: 0 0 0.6 0 15 + Waiting: 0 0 0.6 0 15 + Total: 4 9 4.8 8 61 + + Percentage of the requests served within a certain time (ms) + 50% 8 + 66% 9 + 75% 11 + 80% 12 + 90% 15 + 95% 18 + 98% 22 + 99% 30 + 100% 61 (longest request) + +CodeIgniter 2.1.0 +^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/codeigniter/index.php/say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/codeigniter/index.php/say/hello + Document Length: 16 bytes + + Concurrency Level: 5 + Time taken for tests: 1.159 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 209000 bytes + HTML transferred: 16000 bytes + Requests per second: 862.58 [#/sec] (mean) + Time per request: 5.797 [ms] (mean) + Time per request: 1.159 [ms] (mean, across all concurrent requests) + Transfer rate: 176.05 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 6 3.3 5 34 + Processing: 0 0 1.5 0 34 + Waiting: 0 0 1.5 0 34 + Total: 2 6 3.5 5 35 + + Percentage of the requests served within a certain time (ms) + 50% 5 + 66% 6 + 75% 6 + 80% 7 + 90% 8 + 95% 12 + 98% 17 + 99% 24 + 100% 35 (longest request) + + +Kohana 3.2.0 +^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/kohana/index.php/say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/kohana/index.php/say/hello + Document Length: 15 bytes + + Concurrency Level: 5 + Time taken for tests: 1.375 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 223000 bytes + HTML transferred: 15000 bytes + Requests per second: 727.07 [#/sec] (mean) + Time per request: 6.877 [ms] (mean) + Time per request: 1.375 [ms] (mean, across all concurrent requests) + Transfer rate: 158.34 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 7 3.3 6 37 + Processing: 0 0 0.6 0 10 + Waiting: 0 0 0.4 0 6 + Total: 3 7 3.3 6 37 + + Percentage of the requests served within a certain time (ms) + 50% 6 + 66% 7 + 75% 8 + 80% 8 + 90% 10 + 95% 13 + 98% 16 + 99% 20 + 100% 37 (longest request) + + +Fuel 1.2.1 +^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/fuel/say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/fuel/public/say/hello + Document Length: 16 bytes + + Concurrency Level: 5 + Time taken for tests: 1.759 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 209000 bytes + HTML transferred: 16000 bytes + Requests per second: 568.41 [#/sec] (mean) + Time per request: 8.796 [ms] (mean) + Time per request: 1.759 [ms] (mean, across all concurrent requests) + Transfer rate: 116.01 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 9 4.3 8 51 + Processing: 0 0 1.3 0 34 + Waiting: 0 0 1.3 0 34 + Total: 4 9 4.4 8 51 + + Percentage of the requests served within a certain time (ms) + 50% 8 + 66% 9 + 75% 10 + 80% 11 + 90% 13 + 95% 17 + 98% 22 + 99% 26 + 100% 51 (longest request) + +Cake 2.1.3 +^^^^^^^^^^ + +.. code-block:: php + + # ab -n 10 -c 5 http://localhost/bench/cake/say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient).....done + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/cake/say/hello + Document Length: 16 bytes + + Concurrency Level: 5 + Time taken for tests: 30.051 seconds + Complete requests: 10 + Failed requests: 0 + Write errors: 0 + Total transferred: 1680 bytes + HTML transferred: 160 bytes + Requests per second: 0.33 [#/sec] (mean) + Time per request: 15025.635 [ms] (mean) + Time per request: 3005.127 [ms] (mean, across all concurrent requests) + Transfer rate: 0.05 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 2 3.6 0 11 + Processing: 15009 15020 9.8 15019 15040 + Waiting: 9 21 7.9 25 33 + Total: 15009 15022 8.9 15021 15040 + + Percentage of the requests served within a certain time (ms) + 50% 15021 + 66% 15024 + 75% 15024 + 80% 15032 + 90% 15040 + 95% 15040 + 98% 15040 + 99% 15040 + 100% 15040 (longest request) + +Zend Framework 1.11.11 +^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 10 -c 5 http://localhost/bench/zendfw/public/say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/zendfw/public/say/hello + Document Length: 16 bytes + + Concurrency Level: 5 + Time taken for tests: 3.086 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 209000 bytes + HTML transferred: 16000 bytes + Requests per second: 324.02 [#/sec] (mean) + Time per request: 15.431 [ms] (mean) + Time per request: 3.086 [ms] (mean, across all concurrent requests) + Transfer rate: 66.13 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 15 6.1 14 61 + Processing: 0 0 1.7 0 37 + Waiting: 0 0 1.7 0 36 + Total: 8 15 6.1 14 61 + + Percentage of the requests served within a certain time (ms) + 50% 14 + 66% 16 + 75% 17 + 80% 18 + 90% 23 + 95% 27 + 98% 33 + 99% 37 + 100% 61 (longest request) + +Laravel 3.2.5 +^^^^^^^^^^^^^ + +.. code-block:: php + + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/laravel/public/say/hello + Document Length: 15 bytes + + Concurrency Level: 5 + Time taken for tests: 2.353 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 831190 bytes + HTML transferred: 15000 bytes + Requests per second: 424.97 [#/sec] (mean) + Time per request: 11.765 [ms] (mean) + Time per request: 2.353 [ms] (mean, across all concurrent requests) + Transfer rate: 344.96 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 12 5.6 10 56 + Processing: 0 0 0.6 0 10 + Waiting: 0 0 0.5 0 10 + Total: 5 12 5.6 10 56 + + Percentage of the requests served within a certain time (ms) + 50% 10 + 66% 12 + 75% 13 + 80% 15 + 90% 18 + 95% 22 + 98% 29 + 99% 36 + 100% 56 (longest request) + +Nette 2.0.4 +^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/nette/www/index.php + + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/helloworld/nette/www/index.php + Document Length: 205 bytes + + Concurrency Level: 5 + Time taken for tests: 3.569 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 448000 bytes + HTML transferred: 205000 bytes + Requests per second: 280.18 [#/sec] (mean) + Time per request: 17.846 [ms] (mean) + Time per request: 3.569 [ms] (mean, across all concurrent requests) + Transfer rate: 122.58 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 18 6.6 16 63 + Processing: 0 0 1.0 0 20 + Waiting: 0 0 1.0 0 20 + Total: 9 18 6.6 16 63 + + Percentage of the requests served within a certain time (ms) + 50% 16 + 66% 19 + 75% 20 + 80% 22 + 90% 27 + 95% 31 + 98% 37 + 99% 39 + 100% 63 (longest request) + + +Phalcon Version 0.5.0 +^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/phalcon/index.php?_url=/say/hello + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/phalcon/index.php?_url=/say/hello + Document Length: 16 bytes + + Concurrency Level: 5 + Time taken for tests: 0.419 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 209000 bytes + HTML transferred: 16000 bytes + Requests per second: 2386.74 [#/sec] (mean) + Time per request: 2.095 [ms] (mean) + Time per request: 0.419 [ms] (mean, across all concurrent requests) + Transfer rate: 487.14 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 2 1.1 2 17 + Processing: 0 0 0.1 0 3 + Waiting: 0 0 0.1 0 2 + Total: 1 2 1.1 2 17 + + Percentage of the requests served within a certain time (ms) + 50% 2 + 66% 2 + 75% 2 + 80% 2 + 90% 3 + 95% 4 + 98% 5 + 99% 7 + 100% 17 (longest request) + + +Graphs +^^^^^^ + +The first graph shows how many requests per second each framework was able to accept. The second shows the average time across all concurrent requests. + + +.. raw:: html + + + +
+
+
+
+
+
+ +Conclusion +---------- + +The compiled nature of Phalcon offers extraordinary performance that outperforms all other frameworks measured in these benchmarks. + +.. _get_included_files: http://www.php.net/manual/en/function.get-included-files.php +.. _memory_get_usage: http://php.net/manual/en/function.memory-get-usage.php +.. _Yii: http://www.yiiframework.com/ +.. _Symfony: http://symfony.com/ +.. _CodeIgniter: http://codeigniter.com/ +.. _Kohana: http://kohanaframework.org/index +.. _FuelPHP: http://fuelphp.com/ +.. _CakePHP: http://cakephp.org/ +.. _Laravel: http://www.laravel.com/ +.. _Zend Framework: http://framework.zend.com +.. _Nette: http://nette.org/ + diff --git a/zh/reference/benchmark/micro.rst b/zh/reference/benchmark/micro.rst new file mode 100644 index 000000000000..450ebe96d260 --- /dev/null +++ b/zh/reference/benchmark/micro.rst @@ -0,0 +1,290 @@ +Micro Benchmark +===================== + +How the benchmarks were performed? +---------------------------------- + +We created a "Hello World" benchmark seeking to identify the smallest load overhead of each framework. Similar to the benchmark made with Frameworks. + +Using a route for the HTTP method 'GET' we pass a parameter to a handler returning a "Hello $name" response. + +What measurements were recorded? +-------------------------------- +These were the measurements we record to identify the overall performance of each framework: + +* Requests per second +* Time across all concurrent requests +* Number of included PHP files on a single request (measured using function get_included_files_. +* Memory Usage per request (measured using function memory_get_usage_. + +Pariticipant Frameworks +----------------------- + +* Slim_ +* Silex_ + +Results +------- + +Slim Framework +^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/micro/slim/say/hello/Sonny + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/micro/slim/say/hello/Sonny + Document Length: 13 bytes + + Concurrency Level: 5 + Time taken for tests: 0.882 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 206000 bytes + HTML transferred: 13000 bytes + Requests per second: 1134.21 [#/sec] (mean) + Time per request: 4.408 [ms] (mean) + Time per request: 0.882 [ms] (mean, across all concurrent requests) + Transfer rate: 228.17 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 4 2.4 4 33 + Processing: 0 0 0.5 0 11 + Waiting: 0 0 0.5 0 11 + Total: 2 4 2.4 4 33 + + Percentage of the requests served within a certain time (ms) + 50% 4 + 66% 4 + 75% 5 + 80% 5 + 90% 6 + 95% 8 + 98% 12 + 99% 14 + 100% 33 (longest request) + +Silex +^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/micro/silex/say/hello/Sonny + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/micro/silex/say/hello/Sonny + Document Length: 12 bytes + + Concurrency Level: 5 + Time taken for tests: 2.228 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 225000 bytes + HTML transferred: 12000 bytes + Requests per second: 448.75 [#/sec] (mean) + Time per request: 11.142 [ms] (mean) + Time per request: 2.228 [ms] (mean, across all concurrent requests) + Transfer rate: 98.60 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 11 5.1 10 44 + Processing: 0 0 1.1 0 26 + Waiting: 0 0 1.1 0 26 + Total: 5 11 5.1 10 45 + + Percentage of the requests served within a certain time (ms) + 50% 10 + 66% 12 + 75% 13 + 80% 14 + 90% 17 + 95% 20 + 98% 25 + 99% 29 + 100% 45 (longest request) + +Phalcon 0.5.0 +^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + # ab -n 1000 -c 5 http://localhost/bench/micro/phalcon/say/hello/Sonny + This is ApacheBench, Version 2.3 <$Revision: 655654 $> + Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ + Licensed to The Apache Software Foundation, http://www.apache.org/ + + Benchmarking localhost (be patient) + + + Server Software: Apache/2.2.22 + Server Hostname: localhost + Server Port: 80 + + Document Path: /bench/micro/phalcon/say/hello/Sonny + Document Length: 12 bytes + + Concurrency Level: 5 + Time taken for tests: 0.397 seconds + Complete requests: 1000 + Failed requests: 0 + Write errors: 0 + Total transferred: 205000 bytes + HTML transferred: 12000 bytes + Requests per second: 2516.74 [#/sec] (mean) + Time per request: 1.987 [ms] (mean) + Time per request: 0.397 [ms] (mean, across all concurrent requests) + Transfer rate: 503.84 [Kbytes/sec] received + + Connection Times (ms) + min mean[+/-sd] median max + Connect: 0 2 0.9 2 11 + Processing: 0 0 0.2 0 5 + Waiting: 0 0 0.2 0 4 + Total: 1 2 0.9 2 11 + + Percentage of the requests served within a certain time (ms) + 50% 2 + 66% 2 + 75% 2 + 80% 2 + 90% 3 + 95% 4 + 98% 5 + 99% 5 + 100% 11 (longest request) + + + +Graphs +^^^^^^ + +The first graph shows how many requests per second each framework was able to accept. The second shows the average time across all concurrent requests. + + +.. raw:: html + + + +
+
+
+
+
+
+ +Conclusion +---------- +The compiled nature of Phalcon offers extraordinary performance that outperforms all other frameworks measured in these benchmarks. + +.. _get_included_files: http://www.php.net/manual/en/function.get-included-files.php +.. _memory_get_usage: http://php.net/manual/en/function.memory-get-usage.php +.. _Slim: http://slimframework.com/ +.. _Silex: http://silex.sensiolabs.org/ diff --git a/zh/reference/cache.rst b/zh/reference/cache.rst new file mode 100755 index 000000000000..440acf10f10e --- /dev/null +++ b/zh/reference/cache.rst @@ -0,0 +1,311 @@ +Improving Performance with Cache +================================ +Phalcon provides the :doc:`Phalcon\\Cache ` class allowing faster access to frequently used or already processed data. +:doc:`Phalcon\\Cache ` is written in C, achieving higher performance and reducing the overhead when getting items from the backends. +This class uses an internal structure of frontend and backend components. Front-end components act as input sources or +interfaces, while backend components offer storage options to the class. + +When to implement cache? +------------------------ +Although this component is very fast, implementing it in cases that is not needed could lead to loss of performance than gain. +We recommend you check this cases before use cache: + +* You are making complex calculations that every time return the same result (changing infrequently) +* You are using a lot of helpers and the output generated is almost always the same +* You are accessing database data constantly and these data rarely change + +.. highlights:: + + *NOTE* Even after implementing the cache, you should check the hit ratio of your cache over a period of time. This can easily + be done, especially in the case of Memcache or Apc, with the relevant tools that the backends provide. + +Caching Behavior +---------------- +The caching process is divided into 2 parts: + +* **Frontend**: This part is responsible for checking if a key has expired and perform additional transformations to the data before storing and after retrieving them from the backend- +* **Backend**: This part is responsible for communicating, writing/reading the data required by the frontend. + +Caching Output Fragments +------------------------ +An output fragment is a piece of HTML or text that is cached as is and returned as is. The output is automatically captured +from the ob_* functions or the PHP output so that it can be saved in the cache. The following example demonstrates such usage. +It receives the output generated by PHP and stores it into a file. The contents of the file are refreshed every 172800 seconds (2 days). + +The implementation of this caching mechanism allows us to gain performance by not executing the helper Phalcon\\Tag::linkTo +call every time this piece of code is called. + +.. code-block:: php + + 172800 + )); + + // Create the component that will cache from the "Output" to a "File" backend + // Set the cache file directory - it's important to keep the "/" at the end of + // the value for the folder + $cache = new Phalcon\Cache\Backend\File($frontCache, array( + "cacheDir" => "../app/cache/" + )); + + // Get/Set the cache file to ../app/cache/my-cache.html + $content = $cache->start("my-cache.html"); + + // If $content is null then the content will be generated for the cache + if ($content === null) { + + //Print date and time + echo date("r"); + + //Generate a link to the sign-up action + echo Phalcon\Tag::linkTo( + array( + "user/signup", + "Sign Up", + "class" => "signup-button" + ) + ); + + // Store the output into the cache file + $cache->save(); + + } else { + + // Echo the cached output + echo $content; + } + +*NOTE* In the example above, our code remains the same, echoing output to the user as it has been doing before. Our cache component +transparently captures that output and stores it in the cache file (when the cache is generated) or it sends it back to the user +pre-compiled from a previous call, thus avoiding expensive operations. + +Caching Arbitrary Data +---------------------- +Caching just data is equally important for your application. Caching can reduce database load by reusing commonly used (but not updated) data, +thus speeding up your application. + +File Backend Example +^^^^^^^^^^^^^^^^^^^^ +One of the caching adapters is 'File'. The only key area for this adapter is the location of where the cache files will be stored. +This is controlled by the cacheDir option which *must* have a backslash at the end of it. + +.. code-block:: php + + 172800 + )); + + // Create the component that will cache "Data" to a "File" backend + // Set the cache file directory - important to keep the "/" at the end of + // of the value for the folder + $cache = new Phalcon\Cache\Backend\File($frontCache, array( + "cacheDir" => "../app/cache/" + )); + + // Try to get cached records + $cacheKey = 'robots_order_id.cache'; + $robots = $cache->get($cacheKey); + if ($robots === null) { + + // $robots is null due to cache expiration or data does not exist + // Make the database call and populate the variable + $robots = Robots::find(array("order" => "id")); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + +Memcached Backend Example +^^^^^^^^^^^^^^^^^^^^^^^^^ +The above example changes slightly (especially in terms of configuration) when we are using a Memcached backend. + +.. code-block:: php + + 3600 + )); + + // Create the component that will cache "Data" to a "Memcached" backend + // Memcached connection settings + $cache = new Phalcon\Cache\Backend\Memcached($frontCache, array( + "host" => "localhost", + "port" => "11211" + )); + + // Try to get cached records + $cacheKey = 'robots_order_id.cache'; + $robots = $cache->get($cacheKey); + if ($robots === null) { + + // $robots is null due to cache expiration or data does not exist + // Make the database call and populate the variable + $robots = Robots::find(array("order" => "id")); + + // Store it in the cache + $cache->save($cacheKey, $robots); + } + + // Use $robots :) + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + +Querying the cache +------------------ +The elements added to the cache are uniquely identified by a key. In the case of the File backend, the key is the +actual filename. To retrieve data from the cache, we just have to call it using the unique key. If the key does +not exist, the get method will return null. + +.. code-block:: php + + get("myProducts"); + +If you want to know which keys are stored in the cache you could call the queryKeys method: + +.. code-block:: php + + queryKeys(); + foreach ($keys as $key) { + $data = $cache->get($key); + echo "Key=", $key, " Data=", $data; + } + + //Query keys in the cache that begins with "my-prefix" + $keys = $cache->queryKeys("my-prefix"); + + +Deleting data from the cache +---------------------------- +There are times where you will need to forcibly invalidate a cache entry (due to an update in the cached data). +The only requirement is to know the key that the data has been stored with. + +.. code-block:: php + + queryKeys("someKey"); + + // Delete all items from the cache + $keys = $cache->queryKeys(); + foreach ($keys as $key) { + $cache->delete($key); + } + + +Checking cache existance +------------------------ +It is possible to check if cache is already exists with given key. + +.. code-block:: php + + exists("someKey")) { + echo $cache->get("someKey"); + } + else { + echo "Cache does not exists!"; + } + + +Frontend Adapters +----------------- +The available frontend adapters that are used as interfaces or input sources to the cache are: + ++---------+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+ +| Adapter | Description | Example | ++=========+================================================================================================================================+================================================================================+ +| Output | Read input data from standard PHP output | :doc:`Phalcon\\Cache\\Frontend\\Output <../api/Phalcon_Cache_Frontend_Output>` | ++---------+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+ +| Data | It's used to cache any kind of PHP data (big arrays, objects, text, etc). The data is serialized before stored in the backend. | :doc:`Phalcon\\Cache\\Frontend\\Data <../api/Phalcon_Cache_Frontend_Data>` | ++---------+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+ +| Base64 | It's used to cache binary data. The data is serialized using base64_encode before be stored in the backend. | :doc:`Phalcon\\Cache\\Frontend\\Base64 <../api/Phalcon_Cache_Frontend_Base64>` | ++---------+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+ +| None | It's used to cache any kind of PHP data without serializing them. | :doc:`Phalcon\\Cache\\Frontend\\Data <../api/Phalcon_Cache_Frontend_None>` | ++---------+--------------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------+ + +Backend Adapters +---------------- +The backend adapters available to store cache data are: + ++-----------+------------------------------------------------+------------+---------------------+-----------------------------------------------------------------------------------+ +| Adapter | Description | Info | Required Extensions | Example | ++===========+================================================+============+=====================+===================================================================================+ +| File | Stores data to local plain files | | | :doc:`Phalcon\\Cache\\Backend\\File <../api/Phalcon_Cache_Backend_File>` | ++-----------+------------------------------------------------+------------+---------------------+-----------------------------------------------------------------------------------+ +| Memcached | Stores data to a memcached server | Memcached_ | memcache_ | :doc:`Phalcon\\Cache\\Backend\\Memcache <../api/Phalcon_Cache_Backend_Memcache>` | ++-----------+------------------------------------------------+------------+---------------------+-----------------------------------------------------------------------------------+ +| APC | Stores data to the Alternative PHP Cache (APC) | APC_ | `APC extension`_ | :doc:`Phalcon\\Cache\\Backend\\Apc <../api/Phalcon_Cache_Backend_Apc>` | ++-----------+------------------------------------------------+------------+---------------------+-----------------------------------------------------------------------------------+ +| Mongo | Stores data to Mongo Database | MongoDb_ | `Mongo`_ | :doc:`Phalcon\\Cache\\Backend\\Mongo <../api/Phalcon_Cache_Backend_Mongo>` | ++-----------+------------------------------------------------+------------+---------------------+-----------------------------------------------------------------------------------+ + +File Backend Options +^^^^^^^^^^^^^^^^^^^^ +This backend will store cached content into files in the local server. The available options for this backend are: + ++----------+-----------------------------------------------------------+ +| Option | Description | ++==========+===========================================================+ +| cacheDir | A writable directory on which cached files will be placed | ++----------+-----------------------------------------------------------+ + +Memcached Backend Options +^^^^^^^^^^^^^^^^^^^^^^^^^ +This backend will store cached content on a memcached server. The available options for this backend are: + ++------------+---------------------------------------------+ +| Option | Description | ++============+=============================================+ +| host | memcached host | ++------------+---------------------------------------------+ +| port | memcached port | ++------------+---------------------------------------------+ +| persistent | create a persitent connection to memcached? | ++------------+---------------------------------------------+ + +APC Backend Options +^^^^^^^^^^^^^^^^^^^ +This backend will store cached content on Alternative PHP Cache (APC_). This cache backend does not require any additional configuration options. + +Mongo Backend Options +^^^^^^^^^^^^^^^^^^^^^^^^^ +This backend will store cached content on a MongoDB server. The available options for this backend are: + ++------------+---------------------------------------------+ +| Option | Description | ++============+=============================================+ +| server | A MongoDB connection string | ++------------+---------------------------------------------+ +| db | Mongo database name | ++------------+---------------------------------------------+ +| collection | Mongo collection in the database | ++------------+---------------------------------------------+ + +.. _Memcached: http://php.net/manual/en/book.apc.php +.. _memcache: http://pecl.php.net/package/memcache +.. _APC: http://php.net/manual/en/book.apc.php +.. _APC extension: http://pecl.php.net/package/APC +.. _MongoDb: http://mongodb.org/ +.. _Mongo: http://pecl.php.net/package/mongo diff --git a/zh/reference/cli.rst b/zh/reference/cli.rst new file mode 100644 index 000000000000..a646b7074682 --- /dev/null +++ b/zh/reference/cli.rst @@ -0,0 +1,37 @@ +Command Line Applications +========================= + +CLI applications are executed from the command line. They are useful to create cron jobs, scripts, command utilities and more. + +Tasks +----- +Tasks are similar to controllers, on them can be implemented + +.. code-block:: php + + setDI($di); + + // + $console->handle(array('shell_script_name', 'echo')); + diff --git a/zh/reference/config.rst b/zh/reference/config.rst new file mode 100755 index 000000000000..08f885d59421 --- /dev/null +++ b/zh/reference/config.rst @@ -0,0 +1,88 @@ +Reading Configuration +===================== +:doc:`Phalcon\\Config <../api/Phalcon_Config>` is a component used to read configuration files of various formats (using adapters) into PHP objects for use in an application. + +File Adapters +------------- +The adapters available are: + ++-----------+---------------------------------------------------------------------------------------------------+ +| File Type | Description | ++===========+===================================================================================================+ +| Ini | Uses INI files to store settings. Internally the adapter uses the PHP function parse_ini_file. | ++-----------+---------------------------------------------------------------------------------------------------+ +| Array | Uses PHP multidimensional arrays to store settings. This adapter offers the best performance. | ++-----------+---------------------------------------------------------------------------------------------------+ + +Native Arrays +------------- +The next example shows how to convert native arrays into Phalcon\\Config objects. This option offers the best performance since no files are read during this request. + +.. code-block:: php + + array( + "adapter" => "Mysql", + "host" => "localhost", + "username" => "scott", + "password" => "cheetah", + "name" => "test_db", + ), + "app" => array( + "controllersDir" => "../app/controllers/", + "modelsDir" => "../app/models/", + "viewsDir" => "../app/views/", + ), + "mysetting" => "the-value" + ); + + $config = new \Phalcon\Config($settings); + + echo $config->app->controllersDir, "\n"; + echo $config->database->username, "\n"; + echo $config->mysetting, "\n"; + +If you want to better organize your project you can save the array in another file and then read it. + +.. code-block:: php + + phalcon->controllersDir, "\n"; + echo $config->database->username, "\n"; + echo $config->models->metadata->adapter, "\n"; + diff --git a/zh/reference/controllers.rst b/zh/reference/controllers.rst new file mode 100755 index 000000000000..7507c6166164 --- /dev/null +++ b/zh/reference/controllers.rst @@ -0,0 +1,310 @@ + +Using Controllers +================= +The controllers provide a number of methods that are called actions. Actions are methods on a controller that handle requests. By default all public methods on a controller map to actions and are accessible by a URL. Actions are responsible for interpreting the request and creating the response. Usually responses are in the form of a rendered view, but there are other ways to create responses as well. + +For instance, when you access a URL like this: http://localhost/blog/posts/show/2012/the-post-title Phalcon by default will decompose each part like this: + ++------------------------+----------------+ +| **Phalcon Directory** | blog | ++------------------------+----------------+ +| **Controller** | posts | ++------------------------+----------------+ +| **Action** | show | ++------------------------+----------------+ +| **Parameter** | 2012 | ++------------------------+----------------+ +| **Parameter** | the-post-title | ++------------------------+----------------+ + +In this case, the PostsController will handle this request. There is no a special location to put controllers in an application, they could be loaded using :doc:`autoloaders `, so you're free to organize your controllers as you need. + +Controllers must have the suffix "Controller" while actions the suffix "Action". A sample of a controller is as follows: + +.. code-block:: php + + `. By doing this, the controller can have easy access to the application services. + +Dispatch Loop +------------- +The dispatch loop will be executed within the Dispatcher until there are no actions left to be executed. In the previous example only one action was executed. Now we'll see how "forward" can provide a more complex flow of operation in the dispatch loop, by forwarding execution to a different controller/action. + +.. code-block:: php + + flash->error("You don't have permission to access this area"); + + // Forward flow to another action + $this->dispatcher->forward(array("controller" => "users", "action" => "signin")); + } + + } + +If users don't have permissions to access a certain action then will be forwarded to the Users controller, signin action. + +.. code-block:: php + + `. + +Initializing Controllers +------------------------ +:doc:`Phalcon\\Mvc\\Controller <../api/Phalcon_Mvc_Controller>` offers the initialize method, which is executed first, before any +action is executed on a controller. The use of the "__construct" method is not recommended. + +.. code-block:: php + + settings = array( + "mySetting" => "value" + ); + } + + public function saveAction() + { + if ($this->settings["mySetting"] == "value") { + //... + } + } + + } + +Injecting Services +------------------ +If a controller extends :doc:`Phalcon\\Mvc\\Controller <../api/Phalcon_Mvc_Controller>` then it have easy access to the service +container in application. For example, if we have registered a service like this: + +.. code-block:: php + + set('storage', function(){ + return new Storage('/some/directory'); + }); + +Then, we can access to that service by this way: + +.. code-block:: php + + storage->save('/some/file'); + + //Accessing the service from the DI + $this->di->get('storage')->save('/some/file'); + + //Another way to access the service + $this->di->getStorage()->save('/some/file'); + } + + } + +If you're using Phalcon as a full-stack framework, you can read the services provided :doc:`by default ` in the framework. + +Request and Response +-------------------- +Assuming that the framework provides a set of pre-registered services. We explain how to interact with the HTTP environment. +The "request" service contains an instance of :doc:`Phalcon\\Http\\Request <../api/Phalcon_Http_Request>` and the "response" +contains a :doc:`Phalcon\\Http\\Response <../api/Phalcon_Http_Response>` representing what is going to be sent back to the client. + +.. code-block:: php + + request->isPost() == true) { + // Access POST data + $customerName = $this->request->getPost("name"); + $customerBorn = $this->request->getPost("born"); + } + } + + } + +The response object is not usually used directly, but is built up before the execution of the action, sometimes - like in +an afterDispatch event - it can be useful to access the response directly: + +.. code-block:: php + + response->setStatusCode(404, "Not Found"); + } + + } + +Learn more about the HTTP environment in their dedicated articles :doc:`request ` and :doc:`response `. + +Session Data +------------ +Sessions help us maintain persistent data between requests. You could access a :doc:`Phalcon\\Session\\Bag <../api/Phalcon_Session_Bag>` +from any controller to encapsulate data that need to be persistent. + +.. code-block:: php + + persistent->name = "Michael"; + } + + public function welcomeAction() + { + echo "Welcome, ", $this->persistent->name; + } + + } + +Using Services as Controllers +----------------------------- +Services may act as controllers, controllers classes are always requested from the services container. Accordingly, +any other class registered with its name can easily replace a controller: + +.. code-block:: php + + set('IndexController', function() { + $component = new Component(); + return $component; + }); + +Creating a Base Controller +-------------------------- +Some application features like access control lists, translation, cache, and template engines are often common to many +controllers. In cases like these the creation of a "base controller" is encouraged to ensure your code stays DRY_. A base +controller is simply a class that extends the :doc:`Phalcon\\Mvc\\Controller <../api/Phalcon_Mvc_Controller>` and encapsulates +the common functionality that all controllers must have. In turn, your controllers extend the "base controller" and have +access to the common functionality. + +This class could be located anywhere, but for organizational conventions we recommend it to be in the controllers folder, +e.g. apps/controllers/ControllerBase.php. We may require this file directly in the bootstrap file or cause to be +loaded using any autoloader: + +.. code-block:: php + + ` is the component behind :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` that powers the model layer in the framework. It consists of an independent high-level abstraction layer for database systems completely written in C. + +This component allows for a lower level database manipulation than using traditional models. + +.. highlights:: + This guide is not intended to be a complete documentation of available methods and their arguments. Please visit the :doc:`API <../api/index>` for a complete reference. + +Database Adapters +----------------- +This component makes use of adapters to encapsulate specific database system details. Phalcon uses PDO_ to connect to databases. The following database engines are supported: + ++------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------+ +| Name | Description | API | ++============+======================================================================================================================================================================================================================================+=========================================================================================+ +| MySQL | Is the world's most used relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases | :doc:`Phalcon\\Db\\Adapter\\Pdo\\Mysql <../api/Phalcon_Db_Adapter_Pdo_Mysql>` | ++------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------+ +| PostgreSQL | PostgreSQL is a powerful, open source relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. | :doc:`Phalcon\\Db\\Adapter\\Pdo\\Postgresql <../api/Phalcon_Db_Adapter_Pdo_Postgresql>` | ++------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------+ +| SQLite | SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine | :doc:`Phalcon\\Db\\Adapter\\Pdo\\Sqlite <../api/Phalcon_Db_Adapter_Pdo_Sqlite>` | ++------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------+ + +Database Dialects +----------------- +Phalcon encapsulates the specific details of each database engine in dialects. Those provide common functions and SQL generator to the adapters. + ++------------+-----------------------------------------------------+--------------------------------------------------------------------------------+ +| Name | Description | API | ++============+=====================================================+================================================================================+ +| MySQL | SQL specific dialect for MySQL database system | :doc:`Phalcon\\Db\\Dialect\\Mysql <../api/Phalcon_Db_Dialect_Mysql>` | ++------------+-----------------------------------------------------+--------------------------------------------------------------------------------+ +| PostgreSQL | SQL specific dialect for PostgreSQL database system | :doc:`Phalcon\\Db\\Dialect\\Postgresql <../api/Phalcon_Db_Dialect_Postgresql>` | ++------------+-----------------------------------------------------+--------------------------------------------------------------------------------+ +| SQLite | SQL specific dialect for SQLite database system | :doc:`Phalcon\\Db\\Dialect\\Sqlite <../api/Phalcon_Db_Dialect_Sqlite>` | ++------------+-----------------------------------------------------+--------------------------------------------------------------------------------+ + +Connecting to Databases +----------------------- +To create a connection it's neccesary instantiate the adapter class. It only requires an array with the connection parameters. The example below shows how to create a connection passing both required and optional parameters: + +.. code-block:: php + + "127.0.0.1", + "username" => "mike", + "password" => "sigma", + "dbname" => "test_db" + ); + + // Optional + $config["persistent"] = false; + + // Create a connection + $connection = \Phalcon\Db\Adapter\Pdo\Mysql($config); + +.. code-block:: php + + "localhost", + "username" => "postgres", + "password" => "secret1", + "dbname" => "template" + ); + + // Optional + $config["schema"] = "public"; + + // Create a connection + $connection = \Phalcon\Db\Adapter\Pdo\Postgresql($config); + +.. code-block:: php + + "/path/to/database.db" + ); + + // Create a connection + $connection = \Phalcon\Db\Adapter\Pdo\Sqlite($config); + +Finding Rows +------------ +:doc:`Phalcon\\Db <../api/Phalcon_Db>` provides several methods to query rows from tables. The specific SQL syntax of the target database engine is required in this case: + +.. code-block:: php + + query($sql); + + // Print each robot name + while ($robot = $result->fetchArray()) { + echo $robot["name"]; + } + + // Get all rows in an array + $robots = $connection->fetchAll($sql); + foreach ($robots as $robot) { + echo $robot["name"]; + } + + // Get only the first row + $robot = $connection->fetchOne($sql); + +By default these calls create arrays with both associative and numeric indexes. You can change this behavior by using Phalcon\\Db\\Result::setFetchMode(). This method receives a constant, defining which kind of index is required. + ++--------------------------+-----------------------------------------------------------+ +| Constant | Description | ++==========================+===========================================================+ +| Phalcon\\Db::FETCH_NUM | Return an array with numeric indexes | ++--------------------------+-----------------------------------------------------------+ +| Phalcon\\Db::FETCH_ASSOC | Return an array with associative indexes | ++--------------------------+-----------------------------------------------------------+ +| Phalcon\\Db::FETCH_BOTH | Return an array with both associative and numeric indexes | ++--------------------------+-----------------------------------------------------------+ + +.. code-block:: php + + query($sql); + + $result->setFetchMode(Phalcon\Db::DB_NUM); + while ($robot = $result->fetchArray()) { + echo $robot[0]; + } + +The Phalcon\\Db::query() returns an instance of :doc:`Phalcon\\Db\\Result\\Pdo <../api/Phalcon_Db_Result_Pdo>`. These objects encapsulate all the functionality related to the returned resultset i.e. traversing, seeking specific records, count etc. + +.. code-block:: php + + query($sql); + + // Traverse the resultset + while ($robot = $result->fetchArray()) { + echo $robot["name"]; + } + + // Seek to the third row + $result->seek(2); + $robot = $result->fetchArray(); + + // Count the resultset + echo $result->numRows(); + + +Binding Parameters +------------------ +Bound parameters is also supported in :doc:`Phalcon\\Db <../api/Phalcon_Db>`. Although there is a minimal performance impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows: + +.. code-block:: php + + bindParams($sql, array(1 => "Wall-E")); + $result = $connection->query($sql); + + // Binding with named placeholders + $sql = "INSERT INTO `robots`(name`, year) VALUES (:name:, :year:)"; + $sql = $connection->bindParams($sql, array("name" => "Astro Boy", "year" => 1952)); + $success = $connection->query($sql); + +When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case "1" or "2" +are considered strings and not numbers, so the placeholder could not be successfully replaced. With any adapter +data are automatically escaped using `PDO Quote `_. + +This function takes into account the connection charset, so its recommended to define the correct charset +in the connection parameters or in your database server configuration, as a wrong +charset will produce undesired effects when storing or retrieving data. + +Also, you can pass your parameterers directly to the execute/query methods. In this case +bound parameters are directly passed to PDO: + +.. code-block:: php + + query($sql, array(1 => "Wall-E")); + + +Inserting/Updating/Deleting Rows +-------------------------------- +To insert, update or delete rows, you can use raw SQL or use the preset functions provided by the class: + +.. code-block:: php + + execute($sql); + + //With placeholders + $sql = "INSERT INTO `robots`(`name`, `year`) VALUES (?, ?)"; + $success = $connection->execute($sql, array('Astroy Boy', 1952)); + + // Generating dynamically the necessary SQL + $success = $connection->insert( + "robots", + array("Astro Boy", 1952), + array("name", "year") + ); + + // Updating data with a raw SQL statement + $sql = "UPDATE `robots` SET `name` = 'Astro boy' WHERE `id` = 101"; + $success = $connection->execute($sql); + + //With placeholders + $sql = "UPDATE `robots` SET `name` = ? WHERE `id` = ?"; + $success = $connection->execute($sql, array('Astroy Boy', 101)); + + // Generating dynamically the necessary SQL + $success = $connection->update( + "robots", + array("name") + array("New Astro Boy"), + "id = 101" + ); + + // Deleting data with a raw SQL statement + $sql = "DELETE `robots` WHERE `id` = 101"; + $success = $connection->execute($sql); + + //With placeholders + $sql = "DELETE `robots` WHERE `id` = ?"; + $success = $connection->execute($sql, array(101)); + + // Generating dynamically the necessary SQL + $success = $connection->delete("robots", "id = 101"); + +Database Events +--------------- +:doc:`Phalcon\\Db <../api/Phalcon_Db>` is able to send events to a :doc:`EventsManager ` if it's present. Some events when returning boolean false could stop the active operation. The following events are supported: + ++------------------+-----------------------------------------------------------+---------------------+ +| Event Name | Triggered | Can stop operation? | ++==================+===========================================================+=====================+ +| afterConnect | After a successfully connection to a database system | No | ++------------------+-----------------------------------------------------------+---------------------+ +| beforeQuery | Before send a SQL statement to the database system | Yes | ++------------------+-----------------------------------------------------------+---------------------+ +| afterQuery | After send a SQL statement to database system | No | ++------------------+-----------------------------------------------------------+---------------------+ +| beforeDisconnect | Before close a temporal database connection | No | ++------------------+-----------------------------------------------------------+---------------------+ + +Bind a EventsManager to a connection is simple, Phalcon\\Db will trigger the events with the type "db": + +.. code-block:: php + + attach('db', $dbListener); + + $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + + //Assign the eventsManager to the db adapter instance + $connection->setEventsManager($eventsManager); + +Profiling SQL Statements +------------------------ +:doc:`Phalcon\\Db <../api/Phalcon_Db>` includes a profiling component called :doc:`Phalcon\\Db\\Profiler <../api/Phalcon_Db_Profiler>`, that is used to analyze the performance of database operations so as to diagnose performance problems and discover bottlenecks. + +Database profiling is really easy With :doc:`Phalcon\\Db\\Profiler <../api/Phalcon_Db_Profiler>`: + +.. code-block:: php + + attach('db', function($event, $connection) use ($profiler) { + if ($event->getType() == 'beforeQuery') { + //Start a profile with the active connection + $profiler->startProfile($connection->getSQLStatement()); + } + if ($event->getType() == 'afterQuery') { + //Stop the active profile + $profiler->stopProfile(); + } + }); + + $sql = "SELECT buyer_name, quantity, product_name " + . "FROM buyers " + . "LEFT JOIN products ON buyers.pid = products.id"; + + // Execute a SQL statement + $connection->query($sql); + + // Get the last profile in the profiler + $profile = $profiler->getLastProfile(); + + echo "SQL Statement: ", $profile->getSQLStatement(), "\n"; + echo "Start Time: ", $profile->getInitialTime(), "\n"; + echo "Final Time: ", $profile->getFinalTime(), "\n"; + echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n"; + +You can also create your own profile class based on :doc:`Phalcon\\Db\\Profiler <../api/Phalcon_Db_Profiler>` to record real time statistics of the statements sent to the database system: + +.. code-block:: php + + getSQLStatement(); + } + + /** + * Executed after the SQL statement was sent to the db server + */ + public function afterEndProfile(Item $profile) + { + echo $profile->getTotalElapsedSeconds(); + } + + } + + //Create a EventsManager + $eventsManager = new Phalcon\Events\Manager(); + + //Create a listener + $dbProfiler = new DbProfiler(); + + //Attach the listener listening for all database events + $eventsManager->attach('db', $dbProfiler); + + +Logging SQL Statements +---------------------- +Using high-level abstraction components such as :doc:`Phalcon\\Db <../api/Phalcon_Db>` to access a database, it is difficult to understand which statements are sent to the database system. :doc:`Phalcon\\Logger <../api/Phalcon_Logger>` interacts with :doc:`Phalcon\\Db <../api/Phalcon_Db>`, providing logging capabilities on the database abstraction layer. + +.. code-block:: php + + attach('db', function($event, $connection) use ($logger) { + if ($event->getType() == 'beforeQuery') { + $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); + } + }); + + //Assign the eventsManager to the db adapter instance + $connection->setEventsManager($eventsManager); + + //Execute some SQL statement + $connection->insert( + "products", + array("Hot pepper", 3.50), + array("name", "price") + ); + +As above, the file *app/logs/db.log* will contain something like this: + +.. code-block:: php + + [Sun, 29 Apr 12 22:35:26 -0500][DEBUG][Resource Id #77] INSERT INTO products + (name, price) VALUES ('Hot pepper', 3.50) + + +Implementing your own Logger +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +You can implement your own logger class for database queries, by creating a class that implements a single method called "log". +The method needs to accept a string as the first argument. You can then pass your logging object to Phalcon\\Db::setLogger(), +and from then on any SQL statement executed will call that method to log the results. + +Describing Tables and Databases +------------------------------- +:doc:`Phalcon\\Db <../api/Phalcon_Db>` also provides methods to retrieve detailed information about tables and databases. + +.. code-block:: php + + listTables("test_db"); + + // Is there a table robots in the database? + $exists = $connection->tableExists("robots"); + + // Get name, data types and special features of robots fields + $fields = $connection->describeTable("robots"); + foreach ($fields as $field) { + echo "Column Type: ", $field["Type"]; + } + + // Get indexes on the robots table + $indexes = $connection->describeIndexes("robots"); + foreach ($indexes as $index) { + print_r($index->getColumns()); + } + + // Get foreign keys on the robots table + $references = $connection->describeReferences("robots"); + foreach ($references as $reference) { + // Print referenced columns + print_r($reference->getReferencedColumns()); + } + +A table description is very similar to the MySQL describe command, it contains the following information: + ++-------+----------------------------------------------------+ +| Index | Description | ++=======+====================================================+ +| Field | Field's name | ++-------+----------------------------------------------------+ +| Type | Column Type | ++-------+----------------------------------------------------+ +| Key | Is the column part of the primary key or an index? | ++-------+----------------------------------------------------+ +| Null | Does the column allow null values? | ++-------+----------------------------------------------------+ + + +Creating/Altering/Dropping Tables +--------------------------------- +Different database systems (MySQL, Postgresql etc.) offer the ability to create, alter or drop tables with the use of +commands such as CREATE, ALTER or DROP. The SQL syntax differs based on which database system is used. +:doc:`Phalcon\\Db <../api/Phalcon_Db>` offers a unified interface to alter tables, without the need to +differentiate the SQL syntax based on the target storage system. + +Creating Tables +^^^^^^^^^^^^^^^ + +The following example shows how to create a table: + +.. code-block:: php + + createTable( + "robots", + null, + array( + "columns" => array( + new Column( + "id", + array( + "type" => Column::TYPE_INTEGER, + "size" => 10, + "notNull" => true, + "autoIncrement" => true, + ) + ), + new Column( + "name", + array( + "type" => Column::TYPE_VARCHAR, + "size" => 70, + "notNull" => true, + ) + ), + new Column( + "year", + array( + "type" => Column::TYPE_INTEGER, + "size" => 11, + "notNull" => true, + ) + ) + ) + ) + ); + +Phalcon\\Db::createTable() accepts an associative array describing the table. Columns are defined with the class +:doc:`Phalcon\\Db\\Column <../api/Phalcon_Db_Column>`. The table below shows the options available to define a column: + ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| Option | Description | Optional | ++=================+============================================================================================================================================+==========+ +| "type" | Column type. Must be a Phalcon\\Db\\Column constant (see below for a list) | No | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "size" | Some type of columns like VARCHAR or INTEGER may have a specific size | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "scale" | DECIMAL or NUMBER columns may be have a scale to specify how many decimals should be stored | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "unsigned" | INTEGER columns may be signed or unsigned. This option does not apply to other types of columns | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "notNull" | Column can store null values? | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "autoIncrement" | With this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute. | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "first" | Column must be placed at first position in the column order | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "after" | Column must be placed after indicated column | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ + +Phalcon\\Db supports the following database column types: + +* Phalcon\\Db\Column::TYPE_INTEGER +* Phalcon\\Db\Column::TYPE_DATE +* Phalcon\\Db\\Column::TYPE_VARCHAR +* Phalcon\\Db\\Column::TYPE_DECIMAL +* Phalcon\\Db\\Column::TYPE_DATETIME +* Phalcon\\Db\\Column::TYPE_CHAR +* Phalcon\\Db\\Column::TYPE_TEXT + +The associative array passed in Phalcon\\Db::createTable() can have the possible keys: + ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+----------+ +| Index | Description | Optional | ++==============+========================================================================================================================================+==========+ +| "columns" | An array with a set of table columns defined with :doc:`Phalcon\\Db\\Column <../api/Phalcon_Db_Column>` | No | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "indexes" | An array with a set of table indexes defined with :doc:`Phalcon\\Db\\Index <../api/Phalcon_Db_Index>` | Yes | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "references" | An array with a set of table references (foreign keys) defined with :doc:`Phalcon\\Db\\Reference <../api/Phalcon_Db_Reference>` | Yes | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "options" | An array with a set of table creation options. These options often relate to the database system in which the migration was generated. | Yes | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+----------+ + + +Altering Tables +^^^^^^^^^^^^^^^ +As your application grows, you might need to alter your database, as part of a refactoring or adding new features. +Not all database systems allow to modify existing columns or add columns between two existing ones. :doc:`Phalcon\\Db <../api/Phalcon_Db>` +is limited by these constraints. + +.. code-block:: php + + addColumn( + "robots", + null, + new Column( + "robot_type", + array( + "type" => Column::TYPE_VARCHAR, + "size" => 32, + "notNull" => true, + "after" => "name", + ) + ) + ); + + // Modifying an existing column + $connection->modifyColumn( + "robots", + null, + new Column( + "name", + array( + "type" => Column::TYPE_VARCHAR, + "size" => 40, + "notNull" => true, + ) + ) + ); + + // Deleting the column "name" + $connection->deleteColumn("robots", null, "name"); + + +Dropping Tables +^^^^^^^^^^^^^^^ + +Examples on dropping tables: + +.. code-block:: php + + dropTable("robots"); + + //Drop table robot from database "machines" + $connection->dropTable("robots", "machines"); + +.. _PDO: http://www.php.net/manual/en/book.pdo.php diff --git a/zh/reference/debug.rst b/zh/reference/debug.rst new file mode 100755 index 000000000000..0ff45d0c9b6f --- /dev/null +++ b/zh/reference/debug.rst @@ -0,0 +1,219 @@ +Debugging Applications +====================== +PHP offers tools to debug applications with notices, warnings, errors and exceptions. The `Exception class`_ offers information such as the file, line, message, numeric code, backtrace etc. on where an error occurred. OOP frameworks like Phalcon mainly use this class to encapsulate this functionality and provide information back to the developer or user. + +Despite being written in C, Phalcon runs methods in the PHP userland, providing the debug capability that any other application or framework written in PHP has. + +Catching Exceptions +------------------- +Throughout the tutorials and examples of the Phalcon documentation, there is a common element that is catching exceptions. This is a try/catch block: + +.. code-block:: php + + ` extends the PHP `Exception class`_ and is used to understand whether the exception came from Phalcon or PHP itself. + +All exceptions generated by PHP are based on the `Exception class`_, and have at least the following elements: + +.. code-block:: php + + ` is the same as PHP's `Exception class`_: + +.. code-block:: php + + getMessage(), "\n"; + echo " File=", $e->getFile(), "\n"; + echo " Line=", $e->getLine(), "\n"; + echo $e->getTraceAsString(); + } + +It's therefore easy to find which file and line of the application's code generated the exception, as well as the components involved in generating the exception. + +.. code-block:: html + + PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: NO) + File=/Applications/MAMP/htdocs/invo/public/index.php + Line=74 + #0 [internal function]: PDO->__construct('mysql:host=loca...', 'root', '', Array) + #1 [internal function]: Phalcon\Db\Adapter\Pdo->connect(Array) + #2 /Applications/MAMP/htdocs/invo/public/index.php(74): Phalcon\Db\Adapter\Pdo->__construct(Array) + #3 [internal function]: {closure}() + #4 [internal function]: call_user_func_array(Object(Closure), Array) + #5 [internal function]: Phalcon\DI->_factory(Object(Closure), Array) + #6 [internal function]: Phalcon\DI->get('db', Array) + #7 [internal function]: Phalcon\DI->getShared('db') + #8 [internal function]: Phalcon\Mvc\Model->getConnection() + #9 [internal function]: Phalcon\Mvc\Model::_getOrCreateResultset('Users', Array, true) + #10 /Applications/MAMP/htdocs/invo/app/controllers/SessionController.php(83): Phalcon\Mvc\Model::findFirst('email='demo@pha...') + #11 [internal function]: SessionController->startAction() + #12 [internal function]: call_user_func_array(Array, Array) + #13 [internal function]: Phalcon\Mvc\Dispatcher->dispatch() + #14 /Applications/MAMP/htdocs/invo/public/index.php(114): Phalcon\Mvc\Application->handle() + #15 {main} + +As you can see from the above output the Phalcon's classes and methods are displayed just like any other component, and even show the parameters that were invoked in every call. The method `Exception::getTrace`_ provides additional information if needed. + +Reflection and Instrospection +----------------------------- +Any instance of a Phalcon class offers exactly the same behavior than a PHP normal one. It's possible to use the Reflection API or simply print any object to show how is its internal state: + +.. code-block:: php + + + [_module:protected] => + [_controller:protected] => + [_action:protected] => + [_params:protected] => Array + ( + ) + [_routes:protected] => Array + ( + [0] => Phalcon\Mvc\Router\Route Object + ( + [_pattern:protected] => #^/([a-zA-Z0-9\_]+)[/]{0,1}$# + [_compiledPattern:protected] => #^/([a-zA-Z0-9\_]+)[/]{0,1}$# + [_paths:protected] => Array + ( + [controller] => 1 + ) + + [_methods:protected] => + [_id:protected] => 0 + [_name:protected] => + ) + + [1] => Phalcon\Mvc\Router\Route Object + ( + [_pattern:protected] => #^/([a-zA-Z0-9\_]+)/([a-zA-Z0-9\_]+)(/.*)*$# + [_compiledPattern:protected] => #^/([a-zA-Z0-9\_]+)/([a-zA-Z0-9\_]+)(/.*)*$# + [_paths:protected] => Array + ( + [controller] => 1 + [action] => 2 + [params] => 3 + ) + [_methods:protected] => + [_id:protected] => 1 + [_name:protected] => + ) + ) + [_matchedRoute:protected] => + [_matches:protected] => + [_wasMatched:protected] => + [_defaultModule:protected] => + [_defaultController:protected] => + [_defaultAction:protected] => + [_defaultParams:protected] => Array + ( + ) + ) + + +Using XDebug +------------ +XDebug_ is an amazing tool that complements the debugging of PHP applications. It is also a C extension for PHP, and you can use it together with Phalcon without additional configuration or side effects. + +Once you have xdebug installed, you can use its API to get a more detailed information about exceptions and messages. The following example implements xdebug_print_function_stack to stop the execution and generate a backtrace: + +.. code-block:: php + + request->getPost("name", "string"); + $email = $this->request->getPost("email", "email"); + + // Stop execution and show a backtrace + return xdebug_print_function_stack("stop here!"); + + $user = new Users(); + $user->name = $name; + $user->email = $email; + + // Store and check for errors + $user->save(); + } + + } + +In this instance, Xdebug will also show us the variables in the local scope, and a backtrace as well: + +.. code-block:: php + + Xdebug: stop here! in /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php on line 19 + + Call Stack: + 0.0383 654600 1. {main}() /Applications/MAMP/htdocs/tutorial/public/index.php:0 + 0.0392 663864 2. Phalcon\Mvc\Application->handle() /Applications/MAMP/htdocs/tutorial/public/index.php:37 + 0.0418 738848 3. SignupController->registerAction() /Applications/MAMP/htdocs/tutorial/public/index.php:0 + 0.0419 740144 4. xdebug_print_function_stack() /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php:19 + +Xdebug provides several ways to get debug and trace information regarding the execution of your application using Phalcon. You can check the `XDebug documentation`_ for more information. + +.. _Exception class: http://www.php.net/manual/en/language.exceptions.php +.. _Exception::getTrace: http://www.php.net/manual/en/exception.gettrace.php +.. _XDebug: http://xdebug.org +.. _XDebug documentation: http://xdebug.org/docs \ No newline at end of file diff --git a/zh/reference/di.rst b/zh/reference/di.rst new file mode 100644 index 000000000000..709835d62ecf --- /dev/null +++ b/zh/reference/di.rst @@ -0,0 +1,556 @@ +使用依赖注入 +========================== +下面要讲的这个例子有点长,但可以很好的解释为什么使用Service Container以及DI。首先,我们假设,我们要开发一个组件命名为SomeComponent。这个组件中现在将要注入一个数据库连接。 + +在这个例子中,数据库连接在component中被创建,这种方法是不切实际的,这样做的话,我们将不能改变数据库连接参数及数据库类型等一些参数。 + +.. code-block:: php + + "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + + // ... + } + + } + + $some = new SomeComponent(); + $some->someDbTask(); + +为了解决上面所说的问题,我们需要在使用前创建一个外部连接,并注入到容器中。就目前而言,这看起来是一个很好的解决方案: + +.. code-block:: php + + _connection = $connection; + } + + public function someDbTask() + { + $connection = $this->_connection; + + // ... + } + + } + + $some = new SomeComponent(); + + //Create the connection + $connection = new Connection(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + + //Inject the connection in the component + $some->setConnection($connection); + + $some->someDbTask(); + +现在我们来考虑一个问题,我们在应用程序中的不同地方使用此组件,将多次创建数据库连接。使用一种类似全局注册表的方式,从这获得一个数据库连接实例,而不是使用一次就创建一次。 + +.. code-block:: php + + "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + } + + } + + class SomeComponent + { + + protected $_connection; + + /** + * Sets the connection externally + */ + public function setConnection($connection){ + $this->_connection = $connection; + } + + public function someDbTask() + { + $connection = $this->_connection; + + // ... + } + + } + + $some = new SomeComponent(); + + //Pass the connection defined in the registry + $some->setConnection(Registry::getConnection()); + + $some->someDbTask(); + +现在,让我们来想像一下,我们必须在组件中实现两个方法,首先需要创建一个新的数据库连接,第二个总是获得一个共享连接: + +.. code-block:: php + + "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + } + + /** + * Creates a connection only once and returns it + */ + public static function getSharedConnection() + { + if (self::$_connection===null){ + $connection = self::_createConnection(); + self::$_connection = $connection; + } + return self::$_connection; + } + + /** + * Always returns a new connection + */ + public static function getNewConnection() + { + return self::_createConnection(); + } + + } + + class SomeComponent + { + + protected $_connection; + + /** + * Sets the connection externally + */ + public function setConnection($connection){ + $this->_connection = $connection; + } + + /** + * This method always needs the shared connection + */ + public function someDbTask() + { + $connection = $this->_connection; + + // ... + } + + /** + * This method always needs a new connection + */ + public function someOtherDbTask($connection) + { + + } + + } + + $some = new SomeComponent(); + + //This injects the shared connection + $some->setConnection(Registry::getSharedConnection()); + + $some->someDbTask(); + + //Here, we always pass a new connection as parameter + $some->someOtherDbTask(Registry::getConnection()); + +到此为止,我们已经看到了如何使用依赖注入解决我们的问题。不是在代码内部创建依赖关系,而是让其作为一个参数传递,这使得我们的程序更容易维护,降低程序代码的耦合度,实现一种松耦合。但是从长远来看,这种形式的依赖注入也有一些缺点。 + +例如,如果组件中有较多的依赖关系,我们需要创建多个setter方法传递,或创建构造函数进行传递。另外,每次使用组件时,都需要创建依赖组件,使代码维护不太易,我们编写的代码可能像这样: + +.. code-block:: php + + setConnection($connection); + $some->setSession($session); + $some->setFileSystem($fileSystem); + $some->setFilter($filter); + $some->setSelector($selector); + +我想,我们不得不在应用程序的许多地方创建这个对象。如果你不需要依赖的组件后,我们又要去代码注入部分移除构造函数中的参数或者是setter方法。为了解决这个问题,我们再次返回去使用一个全局注册表来创建组件。但是,在创建对象之前,它增加了一个新的抽象层: + +.. code-block:: php + + _di = $di; + } + + public function someDbTask() + { + + // Get the connection service + // Always returns a new connection + $connection = $this->_di->get('db'); + + } + + public function someOtherDbTask() + { + + // Get a shared connection service, + // this will return the same connection everytime + $connection = $this->_di->getShared('db'); + + //This method also requires a input filtering service + $filter = $this->_db->get('filter'); + + } + + } + + $di = new Phalcon\DI(); + + //Register a "db" service in the container + $di->set('db', function(){ + return new Connection(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + }); + + //Register a "filter" service in the container + $di->set('filter', function(){ + return new Filter(); + }); + + //Register a "session" service in the container + $di->set('session', function(){ + return new Session(); + }); + + //Pass the service container as unique parameter + $some = new SomeComponent($di); + + $some->someTask(); + +现在,该组件只有访问某种service的时候才需要它,如果它不需要,它甚至不初始化,以节约资源。该组件是高度解耦。他们的行为,或者说他们的任何其他方面都不会影响到组件本身。 + +我们的实现办法 +------------ + +Phalcon\\DI 是一个实现了服务的依赖注入功能的组件,它本身也是一个容器。 + +由于Phalcon高度解耦,Phalcon\\DI 是框架用来集成其他组件的必不可少的部分,开发人员也可以使用这个组件依赖注入和管理应用程序中不同类文件的实例。 + +基本上,这个组件实现了 `Inversion of Control`_ 模式。基于此,对象不再以构造函数接收参数或者使用setter的方式来实现注入,而是直接请求服务的依赖注入。这就大大降低了整体程序的复杂性,因为只有一个方法用以获得所需要的一个组件的依赖关系。 + +此外,这种模式增强了代码的可测试性,从而使它不容易出错。 + +在容器中注册服务 +------------------------------------- +框架本身或开发人员都可以注册服务。当一个组件A要求调用组件B(或它的类的一个实例),可以从容器中请求调用组件B,而不是创建组件B的一个实例。 + +这种工作方式为我们提供了许多优点: + +* 我们可以更换一个组件,从他们本身或者第三方轻松创建。 +* 在组件发布之前,我们可以充分的控制对象的初始化,并对对象进行各种设置。 +* 我们可以使用统一的方式从组件得到一个结构化的全局实例 + +服务可以通过以下几种方式注入到容器: + +.. code-block:: php + + set("request", 'Phalcon\Http\Request'); + + //Using an anonymous function, the instance will lazy loaded + $di->set("request", function(){ + return new Phalcon\Http\Request(); + }); + + //Registering directly an instance + $di->set("request", new Phalcon\Http\Request()); + + //Using an array definition + $di->set("request", array( + "className" => 'Phalcon\Http\Request' + )); + +在上面的例子中,当向框架请求访问一个请求数据时,它将首先确定容器中是否存在这个"reqeust"名称的服务。 + +容器会反回一个请求数据的实例,开发人员最终得到他们想要的组件。 + +在上面示例中的每一种方法都有优缺点,具体使用哪一种,由开发过程中的特定场景来决定的。 + +用一个字符串来设定一个服务非常简单,但缺少灵活性。设置服务时,使用数组则提供了更多的灵活性,而且可以使用较复杂的代码。lambda函数是两者之间一个很好的平衡,但也可能导致更多的维护管理成本。 + +Phalcon\\DI 提供服务的延迟加载。除非开发人员在注入服务的时候直接实例化一个对象,然后存存储到容器中。在容器中,通过数组,字符串等方式存储的服务都将被延迟加载,即只有在请求对象的时候才被初始化。 + +.. code-block:: php + + set("db", array( + "className" => "Phalcon\Db\Adapter\Pdo\Mysql", + "parameters" => array( + "parameter" => array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "blog" + ) + ) + )); + + //Using an anonymous function + $di->set("db", function(){ + return new Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "blog" + )); + }); + +以上这两种服务的注册方式产生相同的结果。然后,通过数组定义的,在后面需要的时候,你可以修改服务参数: + +.. code-block:: php + + setParameter("db", 0, array( + "host" => "localhost", + "username" => "root", + "password" => "secret" + )); + +从容器中获得服务的最简单方式就是使用"get"方法,它将从容器中返回一个新的实例: + +.. code-block:: php + + get("request"); + +或者通过下面这种魔术方法的形式调用: + +.. code-block:: php + + getRequest(); + +Phalcon\\DI 同时允许服务重用,为了得到一个已经实例化过的服务,可以使用 getShared() 方法的形式来获得服务。 + +具体的 Phalcon\\Http\\Request 请求示例: + +.. code-block:: php + + getShared("request"); + +参数还可以在请求的时候通过将一个数组参数传递给构造函数的方式: + +.. code-block:: php + + get("MyComponent", array("some-parameter", "other")) + +Factory Default DI +------------------ +虽然Phalcon在解耦方面为我们提供了很大的自由度和灵活性,也许我们只是单纯的把它当作一个full-stack的框架来使用。为了实现这一目标,该框架提供了 Phalcon\\DI 的一个变种 Phalcon\\DI\\FactoryDefault 。这个类会自动注册相应的服务,使各种服务组件绑定到框架。 + +.. code-block:: php + + ` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| router | Routing Service | :doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| url | URL Generator Service | :doc:`Phalcon\\Mvc\\Url <../api/Phalcon_Mvc_Url>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| request | HTTP Request Environment Service | :doc:`Phalcon\\Http\\Request <../api/Phalcon_Http_Request>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| response | HTTP Response Environment Service | :doc:`Phalcon\\Http\\Response <../api/Phalcon_Http_Response>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| filter | Input Filtering Service | :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| flash | Flash Messaging Service | :doc:`Phalcon\\Flash\\Direct <../api/Phalcon_Flash_Direct>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| session | Session Service | :doc:`Phalcon\\Session\\Adapter\\Files <../api/Phalcon_Session_Adapter_Files>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| eventsManager | Events Management Service | :doc:`Phalcon\\Events\\Manager <../api/Phalcon_Events_Manager>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| db | Low-Level Database Connection Service | :doc:`Phalcon\\Db <../api/Phalcon_Db>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| modelsManager | Models Management Service | :doc:`Phalcon\\Mvc\\Model\\Manager <../api/Phalcon_Mvc_Model_Manager>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| modelsMetadata | Models Meta-Data Service | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Memory <../api/Phalcon_Mvc_Model_MetaData_Memory>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ +| transactionManager | Models Transaction Manager Service | :doc:`Phalcon\\Mvc\\Model\\Transaction\\Manager <../api/Phalcon_Mvc_Model_Transaction_Manager>` | ++---------------------+---------------------------------------------+----------------------------------------------------------------------------------------------------+ + +Instantiating classes via the Services Container +------------------------------------------------ +当你向服务容器请求服务的时候,如果在容器中找不到这个服务,它会尝试加载具有相同名称的一个类,通过这种行为,我们可以使用注册为一个服务的形式来获取一个类的实例: + +.. code-block:: php + + set('IndexController', function() { + $component = new Component(); + return $component; + }); + + //Register a controller as a service + $di->set('MyOtherComponent', function() { + //Actually returns another component + $component = new AnotherComponent(); + return $component; + }); + + //Create a instance via the services container + $myComponent = $di->get('MyOtherComponent'); + +你可以利用这个特点,总是通过向服务容器(即使它们没有被注册为服务)请求服务来获得类的实例,DI会通过 autoloader 加载的类返回一个类的实例。 + +Accessing the DI in a static way +-------------------------------- +如果你需要,你还可以通过以下的方式使用DI来创建一个静态函数 + +.. code-block:: php + + getShared('session'); + } + + } + +.. _`Inversion of Control`: http://en.wikipedia.org/wiki/Inversion_of_control \ No newline at end of file diff --git a/zh/reference/dispatching.rst b/zh/reference/dispatching.rst new file mode 100755 index 000000000000..301460e96335 --- /dev/null +++ b/zh/reference/dispatching.rst @@ -0,0 +1,191 @@ +Dispatching Controllers +======================= +:doc:`Phalcon\\Mvc\\Dispatcher <../api/Phalcon_Mvc_Dispatcher>` is the component responsible of instantiate controllers and execute the required actions +on them in an MVC application. Understand its operation and capabilities helps us get more out of the services provided by the framework. + +The Dispatch Loop +----------------- +This is an important process that has much to do with the MVC flow itself, especially with the controller part. The work occurs within the controller +dispatcher. The controller files are read, loaded, instantiated, to then the required actions are executed. If an action forwards the flow to another +controller/action, the controller dispatcher starts again. To better illustrate this, the following example shows approximately the process performed +within :doc:`Phalcon\\Mvc\\Dispatcher <../api/Phalcon_Mvc_Dispatcher>`: + +.. code-block:: php + + ` is able to send events to a :doc:`EventsManager ` if it's present. Events are triggered using the type "dispatch". Some events when returning boolean false could stop the active operation. The following events are supported: + ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ +| Event Name | Triggered | Can stop operation? | ++======================+=============================================================================================================================================================================================================+=====================+ +| beforeDispatchLoop | Triggered before enter in the dispatch loop. At this point the dispatcher don't know if the controller or the actions to be executed exist. The Dispatcher only knows the information passed by the Router. | Yes | ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ +| beforeExecuteRoute | Triggered before execute the controller/action method. At this point the dispatcher has been initialized the controller and know if the action exist. | Yes | ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ +| afterExecuteRoute | Triggered after execute the controller/action method. As operation cannot be stopped, only use this event to make clean up after execute the action | No | ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ +| beforeNotFoundAction | Triggered when the action was not found in the controller | Yes | ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ +| beforeException | Triggered before the dispatcher throws any exception | Yes | ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ +| afterDispatchLoop | Triggered after exit the dispatch loop | No | ++----------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+ + +The :doc:`INVO ` tutorial shows how to take advantage of dispatching events implementing a security filter with :doc:`Acl ` + +The following example demonstrates how to attach listeners to this component: + +.. code-block:: php + + set('dispatcher', function(){ + + //Create an event manager + $eventsManager = new Phalcon\Events\Manager(); + + //Attach a listener for type "dispatch" + $eventsManager->attach("dispatch", function($event, $dispatcher) { + //... + }); + + $dispatcher = new \Phalcon\Mvc\Dispatcher(); + + //Bind the eventsManager to the view component + $dispatcher->setEventsManager($eventsManager); + + return $dispatcher; + }); + +Forwarding to other actions +--------------------------- +The dispatch loop allows us to forward the execution flow to another controller/action. This is very useful to check if the user can +access to certain options, redirect users to other screens or simply reuse code. + +.. code-block:: php + + dispatcher->forward(array("controller" => "post", "action" => "index")); + } + + } + +Keep in mind that making a "forward" is not the same as making an HTTP redirect. Although they apparently got the same result. +The "forward" doesn't reloads the current page, all the redirection occurs in a single request, while the HTTP redirect needs two requests +to complete the process. + +Getting Parameters +------------------ +When a route provides named parameters you can receive them in a controller, a view or any other component that extends +:doc:`Phalcon\\DI\\Injectable <../api/Phalcon_DI_Injectable>`. + +.. code-block:: php + + dispatcher->getParam("title"); + + // Get the post's year passed in the URL as parameter + // also filtering it + $year = $this->dispatcher->getParam("year", "int"); + } + + } + +Handling Not-Found Exceptions +----------------------------- +Using the :doc:`EventsManager ` it's possible to insert a hook point before the dispatcher throws an exception when a controller/action wasn't found. + +.. code-block:: php + + set('dispatcher', function(){ + + //Create/Get an EventManager + $eventsManager = new Phalcon\Events\Manager(); + + //Attach a listener + $eventsManager->attach("dispatch", function($event, $dispatcher, $exception) { + + //The controller exists but the action not + if ($event->getType() == 'beforeNotFoundAction') { + $dispatcher->forward(array( + 'controller' => 'index', + 'action' => 'show404' + )); + return false; + } + + //Alternative way, controller or action doesn't exist + if ($event->getType() == 'beforeException') { + switch ($exception->getCode()) { + case Phalcon\Dispatcher::EXCEPTION_HANDLER_NOT_FOUND: + case Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND: + $dispatcher->forward(array( + 'controller' => 'index', + 'action' => 'show404' + )); + return false; + } + } + }); + + $dispatcher = new Phalcon\Mvc\Dispatcher(); + + //Bind the EventsManager to the dispatcher + $dispatcher->setEventsManager($eventsManager); + + return $dispatcher; + }); + diff --git a/zh/reference/events.rst b/zh/reference/events.rst new file mode 100644 index 000000000000..bd0f2de6d8dc --- /dev/null +++ b/zh/reference/events.rst @@ -0,0 +1,269 @@ +Events Manager +============== + +The purpose of this component is to intercept the execution of most of the components of the framework by creating “hooks point”. These hook +points allow the developer to obtain status information, manipulate data or change the flow of execution during the process of a component. + +Usage Example +------------- +In the following example, we use the EventsManager to listen for events produced in a MySQL connection managed by :doc:`Phalcon\\Db <../api/Phalcon_Db>`. +First of all, we need a listener object to do this. We created a class whose methods are the events we want to listen: + +.. code-block:: php + + attach('db', $dbListener); + + $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + + //Assign the eventsManager to the db adapter instance + $connection->setEventsManager($eventsManager); + + //Send a SQL command to the database server + $connection->query("SELECT * FROM products p WHERE p.status = 1"); + +In order to log all the SQL statements executed by our application, we need to use the event “afterQuery”. The first parameter passed to +the event listener contains contextual information about the event that is running, the second is the connection itself. + +.. code-block:: php + + _logger = new \Phalcon\Logger\Adapter\File("../apps/logs/db.log"); + } + + public function afterQuery($event, $connection) + { + $this->_logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); + } + + } + +As part of this example, we will also implement the Phalcon\\Db\\Profiler to detect the SQL statements that are taking longer to execute than expected: + +.. code-block:: php + + _profiler = new \Phalcon\Db\Profiler(); + $this->_logger = new \Phalcon\Logger\Adapter\File("../apps/logs/db.log"); + } + + public function beforeQuery($event, $connection) + { + $this->_profiler->startProfile($connection->getSQLStatement()); + } + + public function afterQuery($event, $connection) + { + $this->_logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); + $this->_profiler->stopProfile(); + } + + public function getProfiler() + { + return $this->_profiler; + } + + } + +The resulting profile data can be obtained from the listener: + +.. code-block:: php + + query("SELECT * FROM products p WHERE p.status = 1"); + + foreach($dbListener->getProfiler()->getProfiles() as $profile){ + echo "SQL Statement: ", $profile->getSQLStatement(), "\n"; + echo "Start Time: ", $profile->getInitialTime(), "\n" + echo "Final Time: ", $profile->getFinalTime(), "\n"; + echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n"; + } + +In a similar manner we can register an lambda function to perform the task instead of a separate listener class (as seen above): + +.. code-block:: php + + attach('db', function($event, $connection) { + if ($event->getType() == 'afterQuery') { + echo $connection->getSQLStatement(); + } + }); + +Creating components that trigger Events +--------------------------------------- +You can create components in your application that trigger events to a EventsManager. As a consequence, there may exist listeners +that react to these events when generated. In the following example we're creating a component called "MyComponent". +This component is EventsManager aware; when its method "someTask" is executed it triggers two events to any listener in the EventsManager: + +.. code-block:: php + + _eventsManager = $eventsManager; + } + + public function someTask() + { + $this->_eventsManager->fire("my-component:beforeSomeTask", $this); + + // do some task + + $this->_eventsManager->fire("my-component:afterSomeTask", $this); + } + + } + +Note that events produced by this component are prefixed with "my-component". This is a unique word that helps us to +identify events that are generated from certain component. You can even generate events outside of the component with +the same name. Now let's create a listener to this component: + +.. code-block:: php + + setEventsManager($myComponent); + + //Attach the listener to the EventsManager + $eventsManager->attach('my-component', new SomeListener()); + + //Execute methods in the component + $myComponent->someTask(); + +As "someTask" is executed, the two methods in the listener will be executed, producing the following output: + +.. code-block:: php + + Here, beforeSomeTask + Here, afterSomeTask + +Additional data may also passed when triggering an event using the third parameter of "fire": + +.. code-block:: php + + fire("my-component:afterSomeTask", $this, $extraData); + +In a listener the third parameter also receives this data: + +.. code-block:: php + + attach('my-component', function($event, $component, $data) { + print_r($data); + }); + + //Receiving the data from the event context + $eventManager->attach('my-component', function($event, $component) { + print_r($event->getData()); + }); + +If a listener it's only interested in listening a specific type of event you can attach a listener directly: + +.. code-block:: php + + attach('my-component:beforeSomeTask', function($event, $component) { + //... + }); diff --git a/zh/reference/filter.rst b/zh/reference/filter.rst new file mode 100755 index 000000000000..b56ddad754fe --- /dev/null +++ b/zh/reference/filter.rst @@ -0,0 +1,178 @@ +Filtering and Sanitizing +======================== +Sanitizing user input is a critical part of software development. Trusting or neglecting to sanitize user input could lead to unauthorized access to the content of your application, mainly user data, or even the server your application is hosted. + +.. figure:: ../_static/img/sql.png + :align: center + +Full image (from xkcd) + +The :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` component provides a set of commonly used filters and data sanitizing helpers. It provides object-oriented wrappers around the PHP filter extension. + +Sanitizing data +--------------- +Sanitizing is the process which removes specific characters from a value, that are not required or desired by the user or application. By sanitizing input we ensure that application integrity will be intact. + +.. code-block:: php + + sanitize("some(one)@exa\mple.com", "email"); + + // returns "hello" + $filter->sanitize("hello<<", "string"); + + // returns "100019" + $filter->sanitize("!100a019", "int"); + + // returns "100019.01" + $filter->sanitize("!100a019.01a", "float"); + + +Sanitizing from Controllers +--------------------------- +You can access a :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` object from your controllers when accessing GET or POST input data (through the request object). The first parameter is the name of the variable to be obtained; the second is the filter to be applied on it. + +.. code-block:: php + + request->getPost("price", "double"); + + // Sanitizing email from input + $email = $this->request->getPost("customerEmail", "email"); + + } + + } + +Filtering Action Parameters +--------------------------- +The next example shows you how to sanitize the action parameters within a controller action: + +.. code-block:: php + + filter->sanitize($productId, "int"); + } + + } + +Filtering data +-------------- +In addition to sanitizing, :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` also provides filtering by removing or modifying input data to the format we expect. + +.. code-block:: php + + filter("

Hello

", "striptags"); + + // returns "Hello" + $filter->filter(" Hello ", "trim"); + + +Types of Built-in Filters +------------------------- +The following are the built-in filters provided by this component: + ++-----------+---------------------------------------------------------------------------+ +| Name | Description | ++===========+===========================================================================+ +| string | Strip tags | ++-----------+---------------------------------------------------------------------------+ +| email | Remove all characters except letters, digits and !#$%&*+-/=?^_`{|}~@.[]. | ++-----------+---------------------------------------------------------------------------+ +| int | Remove all characters except digits, plus and minus sign. | ++-----------+---------------------------------------------------------------------------+ +| float | Remove all characters except digits, dot, plus and minus sign. | ++-----------+---------------------------------------------------------------------------+ +| alphanum | Remove all characters except [a-zA-Z0-9] | ++-----------+---------------------------------------------------------------------------+ +| striptags | Applies the strip_tags_ function | ++-----------+---------------------------------------------------------------------------+ +| trim | Applies the trim_ function | ++-----------+---------------------------------------------------------------------------+ +| lower | Applies the strtolower_ function | ++-----------+---------------------------------------------------------------------------+ +| upper | Applies the strtoupper_ function | ++-----------+---------------------------------------------------------------------------+ + +Creating your own Filters +------------------------- +You can add your own filters to :doc:`Phalcon\\Filter <../api/Phalcon_Filter>`. The filter function could be an anonomyous function: + +.. code-block:: php + + add('md5', function($value) { + return preg_replace('/[^0-9a-f]/', '', $value); + }); + + //Sanitize with the "md5" filter + $filtered = $filter->sanitize($possibleMd5, "md5"); + +Or, if you prefer, you can implement the filter in a class: + +.. code-block:: php + + add('ipv4', new IPv4Filter()); + + //Sanitize with the "ipv4" filter + $filteredIp = $filter->sanitize("127.0.0.1", "ipv4"); + +Complex Sanitizing and Filtering +-------------------------------- +PHP itself provides an excellent filter extension you can use. Check out its documentation: `Data Filtering at PHP Documentation`_ + +.. _Data Filtering at PHP Documentation: http://www.php.net/manual/en/book.filter.php +.. _strip_tags: http://www.php.net/manual/en/function.strip-tags.php +.. _trim: http://www.php.net/manual/en/function.trim.php +.. _strtolower: http://www.php.net/manual/en/function.strtolower.php +.. _strtoupper: http://www.php.net/manual/en/function.strtoupper.php diff --git a/zh/reference/flash.rst b/zh/reference/flash.rst new file mode 100644 index 000000000000..3255c3801b1b --- /dev/null +++ b/zh/reference/flash.rst @@ -0,0 +1,177 @@ +Flashing Messages +================= +Flash messages are used to notify the user about the state of actions he/she made or simply show information to the users. This kind of +messages can be generated using + +Adapters +-------- +This component makes use of adapters to define the behavior of the messages after being passed to the Flasher: + ++---------+-----------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+ +| Adapter | Description | API | ++=========+===============================================================================================+============================================================================+ +| Direct | Directly outputs the messages passed to the flasher | :doc:`Phalcon\\Flash\\Direct <../api/Phalcon_Flash_Direct>` | ++---------+-----------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+ +| Session | Temporarily stores the messages in session, then messages can be printed in the next request | :doc:`Phalcon\\Flash\\Session <../api/Phalcon_Flash_Session>` | ++---------+-----------------------------------------------------------------------------------------------+----------------------------------------------------------------------------+ + +Usage +----- +Usually the Flash Messaging service is requested from the services container, +if you're using :doc:`Phalcon\\DI\\FactoryDefault <../api/Phalcon_DI_FactoryDefault>` +then :doc:`Phalcon\\Flash\\Direct <../api/Phalcon_Flash_Direct>` is automatically registered as "flash" service: + +.. code-block:: php + + set('flash', function() { + return new \Phalcon\Flash\Direct(); + }); + +This way, you can use it in controllers or views by injecting the service in the required scope: + +.. code-block:: php + + flash->success("The post was correctly saved!"); + } + + } + +There are four built-in message types supported: + +.. code-block:: php + + flash->error("too bad! the form had errors"); + $this->flash->success("yes!, everything went very smoothly"); + $this->flash->notice("this a very important information"); + $this->flash->warning("best check yo self, you're not looking too good."); + +You can add messages with your own types: + +.. code-block:: php + + flash->message("debug", "this is debug message, you don't say"); + +Printing Messages +----------------- +Messages sent to the flasher are automatically formatted with html: + +.. code-block:: html + +
too bad! the form had errors
+
yes!, everything went very smoothly
+
this a very important information
+
best check yo self, you're not looking too good.
+ +As can be seen, also some CSS classes are added automatically to the DIVs. These classes allow you to define the graphical presentation +of the messages in the browser. The CSS classes can be overridden, for example, if you're using Twitter bootrstrap, classes can be configured as: + +.. code-block:: php + + set('flash', function(){ + $flash = new \Phalcon\Flash\Direct(array( + 'error' => 'alert alert-error', + 'success' => 'alert alert-success', + 'notice' => 'alert alert-info', + )); + return $flash; + }); + +Then the messages would be printed as follows: + +.. code-block:: html + +
too bad! the form had errors
+
yes!, everything went very smoothly
+
this a very important information
+ +Implicit Flush vs. Session +-------------------------- +Depending on the adapter used to send the messages, it could be producing output directly, or be temporarily storing the messages in session to be shown later. +When should you use each? That usually depends on the type of redirection you do after sending the messages. For example if you make a "forward" +is not necessary to store the messages in session, but if you do a HTTP redirect then they need to be stored in session: + +.. code-block:: php + + flash->success("Your information were stored correctly!"); + + //Forward to the index action + return $this->dispatcher->forward(array("action" => "index")); + } + + } + +Or using a HTTP redirection: + +.. code-block:: php + + flashSession->success("Your information were stored correctly!"); + + //Make a full HTTP redirection + return $this->response->redirect("contact/index"); + } + + } + +In this case you need to print manually the messages in the corresponding view: + +.. code-block:: html+php + + + +

flashSession->output() ?>

+ +The attribute 'flashSession' is how the flash was previously set into the dependency injector. diff --git a/zh/reference/install.rst b/zh/reference/install.rst new file mode 100755 index 000000000000..7bfa298534b0 --- /dev/null +++ b/zh/reference/install.rst @@ -0,0 +1,109 @@ +安装 +============ + +PHP extensions require a slightly different installation method to a traditional php-based library or framework. You can either download a binary package for the system of your choice or build it from the sources. + +During the last few months, we have extensively researched PHP's behavior, investigating areas for significant optimizations (big or small). Through understanding of the Zend Engine, we managed to remove unecessary validations, compacted code, performed optimizations and generated low-level solutions so as to achieve maximum performance from Phalcon. + +.. highlights:: + Phalcon compiles from PHP 5.3.1, but due to old PHP bugs causing memory leaks, we highly recommend you to use at least PHP 5.3.11 or greater. + +Windows +------- + +在windows上安装任何扩展都是很简单的,安装phalcon也是一样,下载.dll文件,放到extension目录,然后修改php.ini文件,加入以下行: + + extension=php_phalcon.dll + +重启web server. + +以下视频是教你如何一步一步在windows上安装phalcon + +.. raw:: html + +
+ +Related Guides +^^^^^^^^^^^^^^ + +.. toctree:: + :maxdepth: 1 + + xampp + wamp + +Unix/Linux +---------- + +在Unix/Linux操作系统上,你可以很容易的从源代友编译和安装扩展 + +Requirements +^^^^^^^^^^^^ +Prerequisite packages are: + +* PHP 5.x development resources +* GCC compiler (Linux) or Xcode (Mac) +* Git (if not already installed in your system - unless you download the package from GitHub and upload it on your server via FTP/SFTP) + +.. code-block:: bash + + #Ubuntu + sudo apt-get install php5-dev php5-mysql gcc + sudo apt-get install git-core + + #Suse + yast2 -i php5-pear php5-dev php5-mysql gcc + yast2 -i git-core + +Compilation +^^^^^^^^^^^ +Creating the extension: + +.. code-block:: bash + + git clone git://github.com/phalcon/cphalcon.git + cd cphalcon/build + ./install + +(译者备注)./install其实是默认包含了phpize,configure,make,make install命令。如果您的机器中phpize,php-config不在环境命令中,请执行以下操作后再执行./install + +.. code-block:: bash + + ln -s phpdir/bin/phpize /usr/bin + ln -s phpdir/bin/php-cofnig /usr/bin + +phpdir是你的php安装路径。 + +编辑php.ini文件,加入扩展 + +.. code-block:: bash + + extension=phalcon.so + +重启web server,如果是php-fpm,重启php-fpm即可 + +FreeBSD +^^^^^^^ +A port is available for FreeBSD. Just only need these simple line commands to install it: + +.. code-block:: bash + + pkg_add -r phalcon + +or + +.. code-block:: bash + + export CFLAGS="-O2 -fno-delete-null-pointer-checks" + cd /usr/ports/www/phalcon && make install clean + +Installation Notes +^^^^^^^^^^^^^^^^^^ + +Installation notes for Web Servers: + +.. toctree:: + :maxdepth: 1 + + nginx + diff --git a/zh/reference/intl.rst b/zh/reference/intl.rst new file mode 100755 index 000000000000..3413e3bd053c --- /dev/null +++ b/zh/reference/intl.rst @@ -0,0 +1,97 @@ +Internationalization +==================== +Phalcon is written in C as an extension for PHP. There is a PECL_ extension that offers internationalization functions to PHP applications called intl_. Its documentation can be found in the pages of the official `PHP manual`_. + +Phalcon does not offer this functionality, since creating such a component would be replicating existing code. + +In the examples below, we will show you how to implement the intl_ extension's functionality into Phalcon powered applications. + +.. highlights:: + This guide is not intended to be a complete documentation of the intl_ extension. Please visit its the documentation_ of the extension for a reference. + +Find out best available Locale +------------------------------ +There are several ways to find out the best available locale using intl_. One of them is to check the HTTP "Accept-Language" header: + +.. code-block:: php + + format(array(4560)); + + // Prints USD$ 4,560.5 + $formatter = new MessageFormatter("en_US", "USD$ {0, number}"); + echo $formatter->format(array(4560.50)); + + // Prints ARS$ 1.250,25 + $formatter = new MessageFormatter("es_AR", "ARS$ {0, number}"); + echo $formatter->format(array(1250.25)); + +Message formatting using time and date patterns: + +.. code-block:: php + + format($values); + + // Prints "À 15:53:01 le 19 avr. 2012, il y avait une perturbation sur la planète 7." + $pattern = "À {1, time} le {1, date}, il y avait une perturbation sur la planète {0, number}."; + $formatter = new MessageFormatter("fr_FR", $pattern); + echo $formatter->format($values); + +Locale-Sensitive comparison +--------------------------- +The Collator_ class provides string comparison capability with support for appropriate locale-sensitive sort orderings. Check the examples below on the usage of this class: + +.. code-block:: php + + setStrength(Collator::PRIMARY); + $collator->compare("una canción", "una cancion"); + + // Returns that the strings are not equal + $collator->setStrength(Collator::DEFAULT); + $collator->compare("una canción", "una cancion"); + +.. _PECL: http://pecl.php.net/package/intl +.. _intl: http://pecl.php.net/package/intl +.. _PHP manual: http://www.php.net/manual/en/intro.intl.php +.. _documentation: http://www.php.net/manual/en/book.intl.php +.. _MessageFormatter: http://www.php.net/manual/en/class.messageformatter.php +.. _Collator: http://www.php.net/manual/en/class.collator.php \ No newline at end of file diff --git a/zh/reference/license.rst b/zh/reference/license.rst new file mode 100755 index 000000000000..007a82f97d71 --- /dev/null +++ b/zh/reference/license.rst @@ -0,0 +1,13 @@ +License +======= +Phalcon is brought to you by the Phalcon Team! [`Twitter`_ - `Google Plus`_ - `Github`_] + +The Phalcon PHP Framework is released under the `new BSD license`_. Except where otherwise noted, content on this site is licensed under the `Creative Commons Attribution 3.0 License`_. + +If you love Phalcon please return something to the community! :) + +.. _Twitter: https://twitter.com/#!/phalconphp +.. _Google Plus: https://plus.google.com/u/0/102376109340560896457/posts +.. _Github: https://github.com/phalcon +.. _new BSD license: https://github.com/phalcon/cphalcon/blob/master/docs/LICENSE.md +.. _Creative Commons Attribution 3.0 License: http://creativecommons.org/licenses/by/3.0/ \ No newline at end of file diff --git a/zh/reference/linuxtools.rst b/zh/reference/linuxtools.rst new file mode 100644 index 000000000000..b4a2b46dc03a --- /dev/null +++ b/zh/reference/linuxtools.rst @@ -0,0 +1,33 @@ +Phalcon Developer Tools on Linux +================================ +These steps will guide you through the process of installing Phalcon Developer Tools for Linux. + +Prerequisites +------------- +The Phalcon PHP extension is required to run Phalcon Tools. If you haven't installed it yet, please see the :doc:`Installation ` section for instructions. + +Download +-------- +You can download a cross platform package containing the developer tools from the Download_ section. Also you can clone it from Github_. + +Open a terminal and type the commands below: + +.. figure:: ../_static/img/linux-1.png + :align: center + +Then enter the folder where the tools were cloned and execute ". ./phalcon.sh", (don't forget the dot at beginning of the command): + +.. figure:: ../_static/img/linux-2.png + :align: center + +Congratulations you now have Phalcon tools installed! + +Related Guides +^^^^^^^^^^^^^^ + +* :doc:`Using Developer Tools ` +* :doc:`Installation on Windows ` +* :doc:`Installation on Mac ` + +.. _Download: http://phalconphp.com/download +.. _Github: https://github.com/phalcon/phalcon-devtools diff --git a/zh/reference/loader.rst b/zh/reference/loader.rst new file mode 100755 index 000000000000..2755bf6a0dce --- /dev/null +++ b/zh/reference/loader.rst @@ -0,0 +1,192 @@ +Universal Class Loader +====================== +:doc:`Phalcon\\Loader <../api/Phalcon_Loader>` is a component that allows you to load project classes automatically, based on some predefined rules. +Since this component is written in C, it provides the lowest overhead in reading and interpreting external PHP files. + +The behavior of this component is based on the PHP's capability of `autoloading classes`_. If a class that does not exist is used in any part of the +code, a special handler will try to load it. :doc:`Phalcon\\Loader <../api/Phalcon_Loader>` serves as the special handler for this operation. By +loading classes on a need to load basis, the overall performance is increased since the only file reads that occur are for the files needed. This +technique is called `lazy initialization`_. + +With this component you can load files from other projects or vendors, this autoloader is `PSR-0 `_ compliant. + +:doc:`Phalcon\\Loader <../api/Phalcon_Loader>` offers four options to autoload classes. You can use them one at a time or combine them. + +Registering Namespaces +---------------------- +If you're organizing your code using namespaces, or external libraries do so, the registerNamespaces() provides the autoloading mechanism. It +takes an associative array, which keys are namespace prefixes and their values are directories where the classes are located in. The namespace +separator will be replaced by the directory separator when the loader try to find the classes. Remember always to add a trailing slash at +the end of the paths. + +.. code-block:: php + + registerNamespaces( + array( + "Example\Base" => "vendor/example/base/", + "Example\Adapter" => "vendor/example/adapter/", + "Example" => "vendor/example/", + ) + ); + + // register autoloader + $loader->register(); + + // The required class will automatically include the + // file vendor/example/adapter/Some.php + $some = new Example\Adapter\Some(); + +Registering Prefixes +---------------------- +This strategy is similar to the namespaces strategy. It takes an associative array, which keys are prefixes and their values are directories +where the classes are located in. The namespace separator and the "_" underscore character will be replaced by the directory separator when +the loader try to find the classes. Remember always to add a trailing slash at the end of the paths. + +.. code-block:: php + + registerPrefixes( + array( + "Example_Base" => "vendor/example/base/", + "Example_Adapter" => "vendor/example/adapter/", + "Example_" => "vendor/example/", + ) + ); + + // register autoloader + $loader->register(); + + // The required class will automatically include the + // file vendor/example/adapter/Some.php + $some = new Example_Adapter_Some(); + +Registering Directories +----------------------- +The second option is to register directories, in which classes could be found. This option is not recommended in terms of performance, +since Phalcon will need to perform a significant number of file stats on each folder, looking for the file with the same name as the class. +It's important to register the directories in relevance order. Remember always add a trailing slash at the end of the paths. + +.. code-block:: php + + registerDirs( + array( + "library/MyComponent/", + "library/OtherComponent/Other/", + "vendor/example/adapters/", + "vendor/example/" + ) + ); + + // register autoloader + $loader->register(); + + // The required class will automatically include the file from + // the first directory where it has been located + // i.e. library/OtherComponent/Other/Some.php + $some = new Some(); + +Registering Classes +------------------- +The last option is to register the class name and its path. This autoloader can be very useful when the folder convention of the +project does not allow for easy retrieval of the file using the path and the class name. This is the fastest method of autoloading. +However the more your application grows, the more classes/files need to be added to this autoloader, which will effectively make +maintenance of the class list very cumbersome and it is not recommended. + +.. code-block:: php + + registerClasses( + array( + "Some" => "library/OtherComponent/Other/Some.php", + "Example\Base" => "vendor/example/adapters/Example/BaseClass.php", + ) + ); + + // register autoloader + $loader->register(); + + // Requiring a class will automatically include the file it references + // in the associative array + // i.e. library/OtherComponent/Other/Some.php + $some = new Some(); + +Additional file extensions +-------------------------- +Some autoloading strategies such as "prefixes", "namespaces" or "directories" automatically append the "php" extension at the end of the checked file. If you +are using additional extensions you could set it with the method "setExtensions". Files are checked in the order as it were defined: + +.. code-block:: php + + setExtensions(array("php", "inc", "phb")); + +Autoloading Events +------------------ +In the following example, the EventsManager is working with the class loader, allowing us to obtain debugging information regarding the flow of operation: + +.. code-block:: php + + registerNamespaces(array( + 'Example\\Base' => 'vendor/example/base/', + 'Example\\Adapter' => 'vendor/example/adapter/', + 'Example' => 'vendor/example/' + )); + + //Listen all the loader events + $eventsManager->attach('loader', function(){ + if ($event->getType() == 'beforeCheckPath') { + echo $loader->getCheckedPath(); + } + }); + + $loader->setEventsManager($eventsManager); + + $loader->register(); + +Some events when returning boolean false could stop the active operation. The following events are supported: + ++------------------+---------------------------------------------------------------------------------------------------------------------+---------------------+ +| Event Name | Triggered | Can stop operation? | ++==================+=====================================================================================================================+=====================+ +| beforeCheckClass | Triggered before start the autoloading process | Yes | ++------------------+---------------------------------------------------------------------------------------------------------------------+---------------------+ +| pathFound | Triggered when the loader locate a class | No | ++------------------+---------------------------------------------------------------------------------------------------------------------+---------------------+ +| afterCheckClass | Triggered after finish the autoloading process. If this event is launched the autoloader didn't find the class file | No | ++------------------+-----------------------------------------------------------+---------------------------------------------------------+---------------------+ + +.. _autoloading classes: http://www.php.net/manual/en/language.oop5.autoload.php +.. _lazy initialization: http://en.wikipedia.org/wiki/Lazy_initialization diff --git a/zh/reference/logging.rst b/zh/reference/logging.rst new file mode 100755 index 000000000000..1bbcb5432f6b --- /dev/null +++ b/zh/reference/logging.rst @@ -0,0 +1,104 @@ +Logging +======= +:doc:`Phalcon\\Logger <../api/Phalcon_Logger>` is a component whose purpose is to provide logging services for applications. It offers logging to different backends using different adapters. It also offers transaction logging, configuration options, different formats and filters. You can use the :doc:`Phalcon\\Logger <../api/Phalcon_Logger>` for every logging need your application has, from debugging processes to tracing application flow. + +Adapters +-------- +This component makes use of backend adapters to store data. The use of adapters allows for a common interface for logging while switching backends if necessary. The backends supported are: + ++---------+---------------------------+----------------------------------------------------------------------------+ +| Adapter | Description | API | ++=========+===========================+============================================================================+ +| File | Logs to a plain text file | :doc:`Phalcon\\Logger\\Adapter\\File <../api/Phalcon_Logger_Adapter_File>` | ++---------+---------------------------+----------------------------------------------------------------------------+ + +Creating a Log +-------------- +The example below shows how to create a log and add messages to it: + +.. code-block:: php + + log("This is a message"); + $logger->log("This is an error", \Phalcon\Logger::ERROR); + $logger->error("This is another error"); + $logger->close(); + +The log generated is below: + +.. code-block:: php + + [Tue, 17 Apr 12 22:09:02 -0500][DEBUG] This is a message + [Tue, 17 Apr 12 22:09:02 -0500][ERROR] This is an error + [Tue, 17 Apr 12 22:09:02 -0500][ERROR] This is another error + +Transactions +------------ +Logging data to an adapter i.e. File (file system) is always an expensive operation in terms of performance. To combat that, you can take advantage of logging transactions. Transactions store log data temporarily in memory and later on write the data to the relevant adapter (File in this case) in a single atomic operation. + +.. code-block:: php + + begin(); + + // Add messages + $logger->alert("This is an alert"); + $logger->error("This is another error"); + + // Commit messages to file + $logger->commit(); + + $logger->close(); + + +Message Formatting +------------------ +The default logging format is: + +[%date%][%type%] %message% + +:doc:`Phalcon\Logger <../api/Phalcon_Logger>` offers the setFormat() method, which allows you to change the format of the logged messages by defining your own. The log format variables allowed are: + ++-----------+------------------------------------------+ +| Variable | Description | ++===========+==========================================+ +| %message% | The message itself expected to be logged | ++-----------+------------------------------------------+ +| %date% | Date the message was added | ++-----------+------------------------------------------+ +| %type% | Uppercase string with message type | ++-----------+------------------------------------------+ + +The example below shows how to change the log format: + +.. code-block:: php + + setFormat("%date% - %message%"); + +File Logger +----------- +This logger uses plain files to log any kind of data. File handlers are internally open with function `fopen`_. By default all logger files are open using +'ab' mode which open the files for writing only; placing the file pointer at the end of the file. If the file does not exist, attempt to create it. You can +change this mode passing additional options to the constructor: + +.. code-block:: php + + 'w' + )); + +.. _fopen: http://php.net/manual/en/function.fopen.php + diff --git a/zh/reference/mactools.rst b/zh/reference/mactools.rst new file mode 100644 index 000000000000..18f857c01ba2 --- /dev/null +++ b/zh/reference/mactools.rst @@ -0,0 +1,70 @@ +Phalcon Developer Tools on Mac OS X +=================================== +These steps will guide you through the process of installing Phalcon Developer Tools for OS/X. + +Prerequisites +------------- +The Phalcon PHP extension is required to run Phalcon Tools. If you haven't installed it yet, please see the :doc:`Installation ` section for instructions. + +Download +-------- +You can download a cross platform package containing the developer tools from the `Download`_ section. You can also clone it from `Github`_. + +Open the terminal application: + +.. figure:: ../_static/img/mac-1.png + :align: center + +Copy & Paste the commands below in your terminal: + +.. code-block:: bash + + wget -q --no-check-certificate -O phalcon-tools.zip http://github.com/phalcon/phalcon-devtools/zipball/master + unzip -q phalcon-tools.zip + mv phalcon-phalcon-devtools-* phalcon-tools + +Check where the phalcon-tools directory was installed using a *pwd* command in your terminal: + +.. figure:: ../_static/img/mac-2.png + :align: center + +On the Mac platform, you need to configure your user PATH to include Phalcon tools. Edit your .profile and append the Phalcon tools path to the environment variable PATH: + +.. figure:: ../_static/img/mac-3.png + :align: center + +Insert these two lines at the end of the file: + +.. code-block:: bash + + export PATH=$PATH:/Users/scott/phalcon-tools + export PTOOLSPATH=/Users/scott/phalcon-tools + +The .profile should look like this: + +.. figure:: ../_static/img/mac-4.png + :align: center + +Save your changes and close the editor. In the terminal window, type the following commands to create a symbolic link to the phalcon.sh script: + +.. code-block:: bash + + ln -s ~/phalcon-tools/phalcon.sh ~/phalcon-tools/phalcon + chmod +x ~/phalcon-tools/phalcon + +Type the command "phalcon" and you will see something like this: + +.. figure:: ../_static/img/mac-5.png + :align: center + +Congratulations you now have Phalcon tools installed! + +Related Guides +^^^^^^^^^^^^^^ + +* :doc:`Using Developer Tools ` +* :doc:`Installation on Windows ` +* :doc:`Installation on Linux ` + +.. _Download: http://phalconphp.com/download> +.. _Github: https://github.com/phalcon/phalcon-devtools \ No newline at end of file diff --git a/zh/reference/micro.rst b/zh/reference/micro.rst new file mode 100644 index 000000000000..aec6e19a3b6b --- /dev/null +++ b/zh/reference/micro.rst @@ -0,0 +1,334 @@ +Micro Applications +================== +With Phalcon you can create "Micro-Framework like" applications. By doing this, you only need to write a minimal amount of code to create a +PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way. + +.. code-block:: php + + get('/say/welcome/{name}', function ($name) { + echo "

Welcome $name!

"; + }); + + $app->handle(); + +Creating a Micro Application +---------------------------- +:doc:`Phalcon\\Mvc\\Micro <../api/Phalcon_Mvc_Micro>` is the class responsible for implementing a micro application. + +.. code-block:: php + + ` manages routing internally. +Routes must always start with /. A HTTP method constraint to a route can be added, so as to instruct the route to match only the requests +matched to the HTTP methods. The following example shows how to define a route for the method GET: + +.. code-block:: php + + get('/say/hello/{name}', function ($name) { + echo "

Hello! $name

"; + }); + +The "get" method indicates that the associated HTTP method is GET. The route /say/hello/{name} also has a parameter {$name} that is passed +directly to the route handler. Handlers are executed when a route is matched. A handler could be any callable item in the PHP userland. +The following example shows how to defined different types of handlers: + +.. code-block:: php + + Hello! $name"; + } + + $app->get('/say/hello/{name}', "say_hello"); + + // With a static method + $app->get('/say/hello/{name}', "SomeClass::someSayMethod"); + + // With a method in an object + $myController = new MyController(); + $app->get('/say/hello/{name}', array($myController, "someAction")); + + //Anonymous function + $app->get('/say/hello/{name}', function ($name) { + echo "

Hello! $name

"; + }); + +:doc:`Phalcon\\Mvc\\Micro <../api/Phalcon_Mvc_Micro>` provides a set of methods to define the HTTP method (or methods) which the route is constrained for: + +.. code-block:: php + + get('/api/products', "get_products"); + + //Matches if the HTTP method is POST + $app->post('/api/products/add', "add_product"); + + //Matches if the HTTP method is PUT + $app->put('/api/products/update/{id}', "update_product"); + + //Matches if the HTTP method is DELETE + $app->put('/api/products/remove/{id}', "delete_product"); + + //Matches if the HTTP method is OPTIONS + $app->options('/api/products/info/{id}', "info_product"); + + //Matches if the HTTP method is GET or POST + $app->map('/repos/store/refs')->via(array('GET', 'POST')); + + +Routes with Parameters +^^^^^^^^^^^^^^^^^^^^^^ +Defining parameters in routes as very easy as demonstrated above. The parameter name has to be enclosed in brackets. Parameter +formatting is also available using regular expressions to ensure consistency of data. This is demonstrated in the example below: + +.. code-block:: php + + get('/posts/{year:[0-9]+}/{title:[a-zA-Z\-]+}', function ($year, $title) { + echo "

Title: $title

"; + echo "

Year: $year

"; + }); + +Starting Route +^^^^^^^^^^^^^^ +Normally, the starting route in an application will be the / route, and it will more frequent than not be accessed by the method GET. +This scenario is coded as follows: + +.. code-block:: php + + get('/', function () { + echo "

Welcome!

"; + }); + +Rewrite Rules +^^^^^^^^^^^^^ +The following rules can be used together with Apache to rewrite the URis: + +.. code-block:: apacheconf + + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + + +Working with Responses +---------------------- +You are free to produce any kind of responses in a handler: directly make an output, use a template engine, include a view, return a json, etc.: + +.. code-block:: php + + get('/say/hello', function () { + echo "

Hello! $name

"; + }); + + //Requiring another file + $app->get('/show/results', function () { + require 'views/results.php'; + }); + + //Returning a JSON + $app->get('/get/some-json', function () { + echo json_encode(array("some", "important", "data")); + }); + +In addition to that, you have access to the service :doc:`"response" `, with which you can manipulate better the response: + +.. code-block:: php + + get('/show/data', function () use ($app) { + + //Set the Content-Type header + $app->response->setContentType('text/plain')->sendHeaders(); + + //Print a file + readfile("data.txt"); + + }); + +Making redirections +------------------- +Redirections could be performed to forward the execution flow to another route: + +.. code-block:: php + + post('/old/welcome', function () use ($app) { + $app->response->redirect("new/welcome"); + }); + + $app->post('/new/welcome', function () use ($app) { + echo 'This is the new Welcome'; + }); + +Generating URLs for Routes +-------------------------- +:doc:`Phalcon\\Mvc\\Url ` can be used to produce URLs based on the defined routes. You need to set up a name for the route; +by this way the "url" service can produce the corresponding URL: + +.. code-block:: php + + get('/blog/{year}/{title}', function ($year, $title) use ($app) { + + //.. show the post here + + })->setName('show-post'); + + //produce a url somewhere + $app->get('/', function() use ($app){ + + echo $app->url->get(array( + 'for' => 'show-post', + 'title' => 'php-is-a-great-framework', + 'year' => 2012 + )); + + }); + + +Interacting with the Dependency Injector +---------------------------------------- +In the micro application, a :doc:`Phalcon\\DI\\FactoryDefault ` services container is created implicitly; additionally you +can create outside of the application a container to +manipulate its services: + +.. code-block:: php + + set('config', function() { + return new \Phalcon\Config\Adapter\Ini("config.ini"); + }); + + $app = new Phalcon\Mvc\Micro(); + + $app->setDI($di); + + $app->get('/', function () use ($app) { + //Read a setting from the config + echo $app->config->app_name; + }); + + $app->post('/contact', function () use ($app) { + $app->flash->success('Yes!, the contact was made!'); + }); + + +Not-Found Handler +----------------- +When a user tries to access a route that is not defined, the micro application will try to execute the "Not-Found" handler. +An example of that behavior is below: + +.. code-block:: php + + notFound(function () use ($app) { + $app->response->setStatusCode(404, "Not Found")->sendHeaders(); + echo 'This is crazy, but this page was not found!'; + }); + +Models in Micro Applications +---------------------------- +:doc:`Models ` can be used transparently in Micro Applications, only is required an autoloader to load models: + +.. code-block:: php + + registerDirs(array( + __DIR__.'/models/' + ))->register(); + + $app = new \Phalcon\Mvc\Micro(); + + $app->get('/products/find', function(){ + + foreach (Products::find() as $product) { + echo $product->name, '
'; + } + + }); + + $app->handle(); + +Micro Application Events +------------------------ +:doc:`Phalcon\\Mvc\\Micro <../api/Phalcon_Mvc_Micro>` is able to send events to the :doc:`EventsManager ` (if it is present). +Events are triggered using the type "micro". The following events are supported: + ++---------------------+----------------------------------------------------------------------------------------------------------------------------+----------------------+ +| Event Name | Triggered | Can stop operation? | ++=====================+============================================================================================================================+======================+ +| beforeHandleRoute | The main method is just called, at this point the application don't know if there is some matched route | Yes | ++---------------------+----------------------------------------------------------------------------------------------------------------------------+----------------------+ +| beforeExecuteRoute | A route has been matched and it contains a valid handler, at this point the handler has not been executed | Yes | ++---------------------+----------------------------------------------------------------------------------------------------------------------------+----------------------+ +| afterExecuteRoute | Triggered after running the handler | No | ++---------------------+----------------------------------------------------------------------------------------------------------------------------+----------------------+ +| beforeNotFound | Triggered when any of the defined routes match the requested URI | Yes | ++---------------------+----------------------------------------------------------------------------------------------------------------------------+----------------------+ +| afterHandleRoute | Triggered after completing the whole process in a successful way | Yes | ++---------------------+----------------------------------------------------------------------------------------------------------------------------+----------------------+ + +In the following example, we explain how to control the application security using events: + +.. code-block:: php + + attach('micro', function($event, $app) { + + if ($event->getType() == 'beforeExecuteRoute') { + if ($app->session->get('auth') == false) { + $app->flashSession->error("The user isn't authenticated"); + $app->response->redirect("/"); + } + } + + }); + + $app = new Phalcon\Mvc\Micro(); + + //Bind the events manager to the app + $app->setEventsManager($eventsManager); + +:doc:`Creating a Simple REST API ` is a tutorial that explains how to create a micro application to implement a RESTful web service. \ No newline at end of file diff --git a/zh/reference/migrations.rst b/zh/reference/migrations.rst new file mode 100755 index 000000000000..9cfae689b664 --- /dev/null +++ b/zh/reference/migrations.rst @@ -0,0 +1,239 @@ +Database Migrations +=================== +Migrations are a convenient way for you to alter your database in a structured and organized manner. + +.. highlights:: + **Important:** Migrations are available on :doc:`Phalcon Developer Tools ` You need at least Phalcon Framework version 0.5.0 to use developer tools. Also is recommended to have PHP 5.3.11 or greater installed. + +Often in development we need to update changes in production environments. Some of these changes could be database modifications like new fields, new tables, removing indexes, etc. + +When a migration is generated a set of classes are created to describe how your database is structured at that moment. These classes can be used to synchronize the schema structure on remote databases setting your database ready to work with the new changes that your application implements. Migrations describe these transformations using plain PHP. + +.. raw:: html + +
+ +
+ +Schema Dumping +-------------- +The :doc:`Phalcon Developer Tools ` provides scripts to manage migrations (generation, running and rollback). + +The available options for generating migrations are: + +.. figure:: ../_static/img/migrations-1.png + :align: center + +Running this script without any parameters will simply dump every object (tables and views) from your database in migration classes. + +Each migration has a version identifier associated to it. The version number allows us to identify if the migration is newer or older than the current 'version' of our database. Versions also inform Phalcon of the running order when executing a migration. + +.. figure:: ../_static/img/migrations-2.png + :align: center + +When a migration is generated, instructions are displayed on the console to describe the different steps of the migration and the execution time of those statements. At the end, a migration version is generated. + +By default :doc:`Phalcon Developer Tools ` use the *app/migrations* directory to dump the migration files. You can change the location by setting one of the parameters on the generation script. Each table in the database has its respective class generated in a separated file under a directory referring its version: + +.. figure:: ../_static/img/migrations-3.png + :align: center + +Migration Class Anatomy +----------------------- +Each file contains a unique class that extends the Phalcon\\Mvc\\Model\\Migration These classes normally have two methods: up() and down(). Up() performs the migration, while down() rolls it back. + +Up() also contains the *magic* method morphTable(). The magic comes when it recognizes the changes needed to synchronize the actual table in the database to the description given. + +.. code-block:: php + + morphTable( + "products", + array( + "columns" => array( + new Column( + "id", + array( + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "autoIncrement" => true, + "first" => true, + ) + ), + new Column( + "product_types_id", + array( + "type" => Column::TYPE_INTEGER, + "size" => 10, + "unsigned" => true, + "notNull" => true, + "after" => "id", + ) + ), + new Column( + "name", + array( + "type" => Column::TYPE_VARCHAR, + "size" => 70, + "notNull" => true, + "after" => "product_types_id", + ) + ), + new Column( + "price", + array( + "type" => Column::TYPE_DECIMAL, + "size" => 16, + "scale" => 2, + "notNull" => true, + "after" => "name", + ) + ), + ), + "indexes" => array( + new Index( + "PRIMARY", + array("id") + ), + new Index( + "product_types_id", + array("product_types_id") + ) + ), + "references" => array( + new Reference( + "products_ibfk_1", + array( + "referencedSchema" => "invo", + "referencedTable" => "product_types", + "columns" => array("product_types_id"), + "referencedColumns" => array("id"), + ) + ) + ), + "options" => array( + "TABLE_TYPE" => "BASE TABLE", + "ENGINE" => "InnoDB", + "TABLE_COLLATION" => "utf8_general_ci", + ) + ) + ); + } + + } + +The class is called "ProductsMigration_100". Suffix 100 refers to the version 1.0.0. morphTable() receives an associative array with 4 possible sections: + ++--------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| Index | Description | Optional | ++==============+=============================================================================================================================================+==========+ +| "columns" | An array with a set of table columns | No | ++--------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "indexes" | An array with a set of table indexes. | Yes | ++--------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "references" | An array with a set of table references (foreign keys). | Yes | ++--------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "options" | An array with a set of table creation options. These options are often related to the database system in which the migration was generated. | Yes | ++--------------+---------------------------------------------------------------------------------------------------------------------------------------------+----------+ + +Defining Columns +^^^^^^^^^^^^^^^^ +:doc:`Phalcon\\Db\\Column <../api/Phalcon_Db_Column>` is used to define table columns. It encapsulates a wide variety of column related features. Its constructor receives as first parameter the column name and an array describing the column. The following options are available when describing columns: + ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| Option | Description | Optional | ++=================+============================================================================================================================================+==========+ +| "type" | Column type. Must be a :doc:`Phalcon_Db_Column <../api/Phalcon_Db_Column>` constant (see below) | No | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "size" | Some type of columns like VARCHAR or INTEGER may have a specific size | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "scale" | DECIMAL or NUMBER columns may be have a scale to specify how much decimals it must store | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "unsigned" | INTEGER columns may be signed or unsigned. This option does not apply to other types of columns | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "notNull" | Column can store null values? | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "autoIncrement" | With this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute. | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "first" | Column must be placed at first position in the column order | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ +| "after" | Column must be placed after indicated column | Yes | ++-----------------+--------------------------------------------------------------------------------------------------------------------------------------------+----------+ + +Database migrations support the following database column types: + +* Phalcon\\Db\\Column::TYPE_INTEGER +* Phalcon\\Db\\Column::TYPE_DATE +* Phalcon\\Db\\Column::TYPE_VARCHAR +* Phalcon\\Db\\Column::TYPE_DECIMAL +* Phalcon\\Db\\Column::TYPE_DATETIME +* Phalcon\\Db\\Column::TYPE_CHAR +* Phalcon\\Db\\Column::TYPE_TEXT + +Defining Indexes +^^^^^^^^^^^^^^^^ +:doc:`Phalcon\\Db\\Index <../api/Phalcon_Db_Index>` defines table indexes. An index only requires that you define a name for it and a list of its columns. Note that if any index has the name PRIMARY, Phalcon will create a primary key index in that table. + +Defining References +^^^^^^^^^^^^^^^^^^^ +:doc:`Phalcon\\Db\\Reference <../api/Phalcon_Db_Reference>` defines table references (also called foreign keys). The following options can be used to define a reference: + ++---------------------+-----------------------------------------------------------------------------------------------------+----------+ +| Index | Description | Optional | ++=====================+=====================================================================================================+==========+ +| "referencedTable" | It's auto-descriptive. It refers to the name of the referenced table. | No | ++---------------------+-----------------------------------------------------------------------------------------------------+----------+ +| "columns" | An array with the name of the columns at the table that have the reference | No | ++---------------------+-----------------------------------------------------------------------------------------------------+----------+ +| "referencedColumns" | An array with the name of the columns at the referenced table | No | ++---------------------+-----------------------------------------------------------------------------------------------------+----------+ +| "referencedTable" | The referenced table maybe is on another schema or database. This option allows you to define that. | Yes | ++---------------------+-----------------------------------------------------------------------------------------------------+----------+ + +Writing Migrations +------------------ +Migrations aren't only designed to "morph" table. A migration is just a regular PHP class so you're not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records. For more details and examples of individual methods, check the :doc:`database component `. + +.. code-block:: php + + insert( + "products", + array("Malabar spinach", 14.50), + array("name", "price") + ); + } + + } + +Running Migrations +------------------ +Once the generated migrations are uploaded on the target server, you can easily run them as shown in the following example: + +.. figure:: ../_static/img/migrations-4.png + :align: center + +.. figure:: ../_static/img/migrations-5.png + :align: center + +Depending on how outdated is the database with respect to migrations, Phalcon may run multiple migration versions in the same migration process. If you specify a target version, Phalcon will run the required migrations until it reaches the specified version. + diff --git a/zh/reference/models.rst b/zh/reference/models.rst new file mode 100755 index 000000000000..381f550b1a93 --- /dev/null +++ b/zh/reference/models.rst @@ -0,0 +1,1863 @@ +Working with Models +=================== +A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing +the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in +your application. The bulk of your application's business logic will be concentrated in the models. + +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` is the base for all models in a Phalcon application. It provides database independence, basic +CRUD functionality, advanced finding capabilities, and the ability to relate models to one another, among other services. +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` avoids the need of having to use SQL statements because it translates methods dynamically +to the respective database engine operations. + +.. highlights:: + + Models are intended to work on a database high layer of abstraction. If you need to work with databases at a lower level check out the + :doc:`Phalcon\\Db <../api/Phalcon_Db>` component documentation. + +Creating Models +--------------- +A model is a class that extends from :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>`. It must be placed in the models directory. A model +file must contain a single class; its class name should be in camel case notation: + +.. code-block:: php + + `. +This component provides a great deal of functionality to models that inherit it, including basic database +CRUD (Create, Read, Update, Destroy) operations, data validation, as well as sophisticated search support and the ability to relate multiple models +with each other. + +.. highlights:: + + If you're using PHP 5.4 is recommended declare each column that makes part of the model in order to save + memory and reduce the memory allocation. + +By default model "Robots" will refer to the table "robots". If you want to manually specify another name for the mapping table, +you can use the getSource() method: + +.. code-block:: php + + select * from robots; + +----+------------+------------+------+ + | id | name | type | year | + +----+------------+------------+------+ + | 1 | Robotina | mechanical | 1972 | + | 2 | Astro Boy | mechanical | 1952 | + | 3 | Terminator | cyborg | 2029 | + +----+------------+------------+------+ + 3 rows in set (0.00 sec) + +You could find a certain record by its primary key and then print its name: + +.. code-block:: php + + name; + +Once the record is in memory, you can make modifications to its data and then save changes: + +.. code-block:: php + + name = "RoboCop"; + $robot->save(); + +As you can see, there is no need to use raw SQL statements. :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` provides high database +abstraction for web applications. + +Finding Records +--------------- +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` also offers several methods for querying records. The following examples will show you +how to query one or more records from a model: + +.. code-block:: php + + "name")); + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + + // Get first 100 virtual robots ordered by name + $robots = Robots::find(array("type = 'virtual'", "order" => "name", "limit" => 100)); + foreach ($robots as $robot) { + echo $robot->name, "\n"; + } + +You could also use the findFirst() method to get only the first record matching the given criteria: + +.. code-block:: php + + name, "\n"; + + // What's the first mechanical robot in robots table? + $robot = Robots::findFirst("type = 'mechanical'"); + echo "The first mechanical robot name is ", $robot->name, "\n"; + + // Get first virtual robot ordered by name + $robot = Robots::findFirst(array("type = 'virtual'", "order" => "name")); + echo "The first virtual robot name is ", $robot->name, "\n"; + +Both find() and findFirst() methods accept an associative array specifying the search criteria: + +.. code-block:: php + + "name DESC", + "limit" => 30 + ) + ); + + $robots = Robots::find( + array( + "conditions" => "type = ?1", + "bind" => array(1 => "virtual") + ) + ); + +The available query options are: + ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| Parameter | Description | Example | ++=============+==============================================================================================================================================================================================+=========================================================================+ +| conditions | Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon_model assumes the first parameter are the conditions. | "conditions" => "name LIKE 'steve%'" | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| bind | Bind is used together with options, by replacing placeholders and escaping values thus increasing security | "bind" => array("status" => "A", "type" => "some-time") | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| bindTypes | When binding parameters, you can use this parameter to define additional casting to the bound parameters increasing even more the security | "bindTypes" => array(Column::BIND_TYPE_STR, Column::BIND_TYPE_INT) | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| order | Is used to sort the resultset. Use one or more fields separated by commas. | "order" => "name DESC, status" | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| limit | Limit the results of the query to results to certain range | "limit" => 10 | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| group | Allows to collect data across multiple records and group the results by one or more columns | "group" => "name, status" | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| for_update | With this option, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` reads the latest available data, setting exclusive locks on each row it reads | "for_update" => true | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| shared_lock | With this option, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` reads the latest available data, setting shared locks on each row it reads | "shared_lock" => true | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| cache | Cache the resulset, reducing the continuous access to the relational system | "cache" => array("lifetime" => 3600, "key" => "my-find-key") | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ + +If you prefer, there is also available a way to create queries in an object oriented way, instead of using an array of parameters: + +.. code-block:: php + + where("type = :type:") + ->bind(array("type" => "mechanical")) + ->order("name") + ->execute(); + +The static method query() returns a :doc:`Phalcon\\Mvc\\Model\\Criteria <../api/Phalcon_Mvc_Model_Criteria>` object that is friendly with IDE autocompleters. + +Phalcon also offers you the possibility to query records using a high level, object oriented, SQL-like language called :doc:`PHQL `. + +Model Resultsets +^^^^^^^^^^^^^^^^ +While findFirst() returns directly an instance of the called class (when there is data to be returned), the find() method returns a +:doc:`Phalcon\\Mvc\\Model\\Resultset\\Simple <../api/Phalcon_Mvc_Model_Resultset_Simple>`. This is an object that encapsulates all the functionality +a resultset has like traversing, seeking specific records, counting, etc. + +These objects are more powerful than standard arrays. One of the greatest features of the :doc:`Phalcon\\Mvc\\Model\\Resultset <../api/Phalcon_Mvc_Model_Resultset>` +is that at any time there is only one record in memory. This greatly helps in memory management especially when working with large amounts of data. + +.. code-block:: php + + name, "\n"; + } + + // Traversing with a while + $robots->rewind(); + while ($robots->valid()) { + $robot = $robots->current(); + echo $robot->name, "\n"; + $robots->next(); + } + + // Count the resultset + echo count($robots); + + // Alternative way to count the resultset + echo $robots->count(); + + // Move the internal cursor to the third robot + $robots->seek(2); + $robot = $robots->current() + + // Access a robot by its position in the resultset + $robot = $robots[5]; + + // Check if there is a record in certain position + if (isset($robots[3]) { + $robot = $robots[3]; + } + + // Get the first record in the resultset + $robot = robots->getFirst(); + + // Get the last record + $robot = robots->getLast(); + +Phalcon resulsets emulates scrollable cursors, you can get any row just by accessing its position, or seeking the internal pointer to a certain position. +Note that some database systems don't support scrollable cursors, this forces to re-execute the query in order to rewind the cursor to the beginning +and obtain the record at the requested position. Similarly, if a resultset is traversed several times, the query must be executed the same number of times. + +Some database systems drivers like SQLite doesn't support scrollable cursors, additionally, store large query results in memory can +consume many resources, due to this resultsets are obtained from the database in chunks of 32 rows reducing the need to +re-execute the request in several cases. + +Note that resultsets can be serialized and stored in a a cache backend. :doc:`Phalcon\\Cache ` can help with that task. However, +serializing data causes :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` to retrieve all the data from the database in an array, +thus consuming more memory while this process takes place. + +.. code-block:: php + + id; + } + +Binding Parameters +^^^^^^^^^^^^^^^^^^ +Bound parameters are also supported in :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>`. Although there is a minimal performance +impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject +to SQL injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows: + +.. code-block:: php + + "Robotina", "type" => "maid"); + $robots = Robots::find(array($conditions, "bind" => $parameters)); + + // Query robots binding parameters with integer placeholders + $conditions = "name = ?1 AND type = ?2"; + $parameters = array(1 => "Robotina", 2 => "maid"); + $robots = Robots::find(array($conditions, "bind" => $parameters)); + + // Query robots binding parameters with both string and integer placeholders + $conditions = "name = :name: AND type = ?1"; + $parameters = array("name" => "Robotina", 1 => "maid"); + $robots = Robots::find(array($conditions, "bind" => $parameters)); + +When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case "1" or "2" are considered strings +and not numbers, so the placeholder could not be successfully replaced. + +Strings are automatically escaped using PDO_. This function takes into account the connection charset, so its recommended to define +the correct charset in the connection parameters or in the database configuration, as a wrong charset will produce undesired effects +when storing or retrieving data. + +Additionally you can set the parameter "bindTypes", this allows to define how the parameters should be binded according to its data type: + +.. code-block:: php + + "Robotina", "year" => 2008); + $types = array(Phalcon\Db\Column::BIND_TYPE_STR, Phalcon\Db\Column::BIND_TYPE_INT); + $robots = Robots::find(array( + $conditions, + "bind" => $parameters, + "bindTypes" => $types + )); + + +Bound parameters are available for all query methods such as find() and findFirst() but also the calculation methods like count(), sum(), average() etc. + +Relationships between Models +---------------------------- +There are four types of relationships: one-on-one, one-to-many, many-to-one and many-to-many. The relationship may be unidirectional +or bidirectional, and each can be simple (a one to one model) or more complex (a combination of models). The model manager manages +foreign key constraints for these relationships, the definition of these helps referential integrity as well as easy and fast access +of related records to a model. Through the implementation of relations, it is easy to access data in related models from each record +in a uniform way. + +Unidirectional relationships +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Unidirectional relations are those that are generated in relation to one another but not vice versa. + +Bidirectional relations +^^^^^^^^^^^^^^^^^^^^^^^ +The bidirectional relations build relationships in both models and each model defines the inverse relationship of the other. + +Defining relationships +^^^^^^^^^^^^^^^^^^^^^^ +In Phalcon, relationships must be defined in the initialize() method of a model. The methods belongsTo(), hasOne() or hasMany() define +the relationship between one or more fields from the current model to fields in another model. Each of these methods requires 3 +parameters: local fields, referenced model, referenced fields. + ++-----------+----------------------------+ +| Method | Description | ++===========+============================+ +| hasMany | Defines a 1-n relationship | ++-----------+----------------------------+ +| hasOne | Defines a 1-1 relationship | ++-----------+----------------------------+ +| belongsTo | Defines a n-1 relationship | ++-----------+----------------------------+ + +The following schema shows 3 tables whose relations will serve us as an example regarding relationships: + +.. code-block:: sql + + CREATE TABLE `robots` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(70) NOT NULL, + `type` varchar(32) NOT NULL, + `year` int(11) NOT NULL, + PRIMARY KEY (`id`) + ); + + CREATE TABLE `robots_parts` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `robots_id` int(10) NOT NULL, + `parts_id` int(10) NOT NULL, + `created_at` DATE NOT NULL, + PRIMARY KEY (`id`), + KEY `robots_id` (`robots_id`), + KEY `parts_id` (`parts_id`) + ); + + CREATE TABLE `parts` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `name` varchar(70) NOT NULL, + PRIMARY KEY (`id`) + ); + +* The model "Robots" has many "RobotsParts". +* The model "Parts" has many "RobotsParts". +* The model "RobotsParts" belongs to "Robots" and "Parts" models as a one-to-many relation. + +The models with their relations could be implemented as follows: + +.. code-block:: php + + hasMany("id", "RobotsParts", "robots_id"); + } + + } + +.. code-block:: php + + hasMany("id", "RobotsParts", "parts_id"); + } + + } + +.. code-block:: php + + belongsTo("robots_id", "Robots", "id"); + $this->belongsTo("parts_id", "Parts", "id"); + } + + } + +The first parameter indicates the field of the local model used in the relationship; the second indicates the name of the referenced +model and the third the field name in the referenced model. You could also use arrays to define multiple fields in the relationship. + +Taking advantage of relationships +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +When explicitly defining the relationships between models, it is easy to find related records for a particular record. + +.. code-block:: php + + getRobotsParts() as $robotPart) { + echo $robotPart->getParts()->name, "\n"; + } + +Phalcon uses the magic method __call to retrieve data from a relationship. If the called method has a "get" prefix +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` will return a findFirst()/find() result. The following example compares +retrieving related results with using the magic method and without: + +.. code-block:: php + + getRobotsParts(); + + // Only parts that match conditions + $robotsParts = $robot->getRobotsParts("created_at='2012-03-15'"); + + // Or using bound parameters + $robotsParts = $robot->getRobotsParts(array( + "created_at=:date:", + "bind" => array("date" => "2012-03-15" + ))); + + $robotPart = RobotsParts::findFirst(1); + + // RobotsParts model has a n-1 (belongsTo) + // relationship to RobotsParts then + $robot = $robotPart->getRobots(); + +Getting related records manually: + +.. code-block:: php + + id . "'"); + + // Only parts that match conditions + $robotsParts = RobotsParts::find( + "robots_id = '" . $robot->id . "' AND created_at='2012-03-15'" + ); + + $robotPart = RobotsParts::findFirst(1); + + // RobotsParts model has a n-1 (belongsTo) + // relationship to RobotsParts then + $robot = Robots::findFirst("id = '" . $robotPart->robots_id . "'"); + + +The prefix "get" is used to find()/findFirst() related records. You can also use "count" prefix to return an integer denoting the count of the related records: + +.. code-block:: php + + countRobotsParts(), " parts\n"; + +Virtual Foreign Keys +^^^^^^^^^^^^^^^^^^^^ +By default, relationships do not act like database foreign keys, that is, if you try to insert/update a value without having a valid +value in the referenced model, Phalcon will not produce a validation message. You can modify this behavior by adding a fourth parameter +when defining a relationship. + +The RobotsPart model can be changed to demonstrate this feature: + +.. code-block:: php + + belongsTo("robots_id", "Robots", "id", array( + "foreignKey" => true + )); + + $this->belongsTo("parts_id", "Parts", "id", array( + "foreignKey" => array( + "message" => "The part_id does not exist on the parts model" + ) + )); + } + + } + +If you alter a belongsTo() relationship to act as foreign key, it will validate that the values inserted/updated on those fields have a +valid value on the referenced model. Similarly, if a hasMany()/hasOne() is altered it will validate that the records cannot be deleted +if that record is used on a referenced model. + +.. code-block:: php + + hasMany("id", "RobotsParts", "parts_id", array( + "foreignKey" => array( + "message" => "The part cannot be deleted because other robots are using it" + ) + )); + } + + } + +Generating Calculations +----------------------- +Calculations are helpers for commonly used functions of database systems such as COUNT, SUM, MAX, MIN or AVG. +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` allows to use these functions directly from the exposed methods. + +Count examples: + +.. code-block:: php + + "area")); + + // How many employees are in the Testing area? + $rowcount = Employees::count("area = 'Testing'"); + + //Count employees grouping results by their area + $group = Employees::count(array("group" => "area")); + foreach ($group as $row) { + echo "There are ", $group->rowcount, " in ", $group->area; + } + + // Count employees grouping by their area and ordering the result by count + $group = Employees::count( + array( + "group" => "area", + "order" => "rowcount" + ) + ); + +Sum examples: + +.. code-block:: php + + "salary")); + + // How much are the salaries of all employees in the Sales area? + $total = Employees::sum( + array( + "column" => "salary", + "conditions" => "area = 'Sales'" + ) + ); + + // Generate a grouping of the salaries of each area + $group = Employees::sum( + array( + "column" => "salary", + "group" => "area" + ) + ); + foreach ($group as $row) { + echo "The sum of salaries of the ", $group->area, " is ", $group->sumatory; + } + + // Generate a grouping of the salaries of each area ordering + // salaries from higher to lower + $group = Employees::sum( + array( + "column" => "salary", + "group" => "area", + "order" => "sumatory DESC" + ) + ); + +Average examples: + +.. code-block:: php + + "salary")); + + // What is the average salary for the Sales's area employees? + $average = Employees::average( + array( + "column" => "salary", + "conditions" => "area = 'Sales'" + ) + ); + +Max/Min examples: + +.. code-block:: php + + "age")); + + // What is the oldest of employees from the Sales area? + $age = Employees::maximum( + array( + "column" => "age", + "conditions" => "area = 'Sales'" + ) + ); + + // What is the lowest salary of all employees? + $salary = Employees::minimum(array("column" => "salary")); + +Caching Resultsets +^^^^^^^^^^^^^^^^^^ +Access to database systems is often one of the most common bottlenecks in terms of performance. This is due to the complex connection +process that PHP must do in each request to obtain data from the database. A well established technique to avoid the continuous access +to the database is to cache resultsets that don't change frequently in a system with faster access (usually memory). + +When :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` requires a service to cache resultsets, it will request it to the Dependency +Injector Container with the convention name "modelsCache". + +As Phalcon provides a component to cache any kind of data, we'll explain how to integrate it with Models. First you need to register +it as a service in the services container: + +.. code-block:: php + + set('modelsCache', function(){ + + //Cache data for one day by default + $frontCache = new Phalcon\Cache\Frontend\Data(array( + "lifetime" => 86400 + )); + + //Memcached connection settings + $cache = new Phalcon\Cache\Backend\Memcached($frontCache, array( + "host" => "localhost", + "port" => "11211" + )); + + return $cache; + }); + +You have complete control in creating and customizing the cache before being used to record the service as an anonymous function. +Once the cache setup is properly defined you could cache resultsets as follows: + +.. code-block:: php + + true)); + + // Cache the resultset only for 5 minutes + $products = Products::find(array("cache" => 300)); + + // Cache the resultset with a key pre-defined + $products = Products::find(array("cache" => array("key" => "my-products-key"))); + + // Cache the resultset with a key pre-defined and for 2 minutes + $products = Products::find( + array( + "cache" => array( + "key" => "my-products-key", + "lifetime" => 120 + ) + ) + ); + + // Using a custom cache + $products = Products::find(array("cache" => $myCache)); + +By default, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` will create a unique key to store the resultset, using a md5 hash +of the SQL select statement generated internally. This is very practical because it generates a new unique key for every change in +the parameters passed in the object. If you wish to control the cache keys, you could always use the key() parameter as seen in the +example above. The getLastKey() method retrieves the key of the last cached entry so that you can target and retrieve the resultset +later on from the cache.: + +.. code-block:: php + + 3600)); + + // Get last generated key + $automaticKey = $products->getCache()->getLastKey(); + + // Use resultset as normal + foreach($products as $product){ + //... + } + +Cache keys automatically generated by :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` are always prefixed with "phc". This helps +to easily identify the cached entries related to :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>`: + +.. code-block:: php + + getModelsCache(); + + // Get keys created by Phalcon\Mvc\Model + foreach ($cache->queryKeys("phc") as $key) { + echo $key, "\n"; + } + +Note that not all resultsets must be cached. Results that change very frequently should not be cached since they are invalidated very +quickly and caching in that case impacts performance. Additionally, large datasets that do not change frequently could be cached but +that is a decision that the developer has to make based on the available caching mechanism and whether the performance impact to simply +retrieve that data in the first place is acceptable. + +Caching could be also applied to resultsets generated using relationships: + +.. code-block:: php + + getComments(array("cache" => true)); + + // Get comments related to a post, setting lifetime + $comments = $post->getComments(array("cache" => true, "lifetime" => 3600)); + +When a cached resultset needs to be invalidated, you can simply delete it from the cache using the generated key. + +Creating Updating/Records +------------------------- +The method Phalcon\\Mvc\\Model::save() allows you to create/update records according to whether they already exist in the table +associated with a model. The save method is called internally by the create and update methods of :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>`. +For this to work as expected it is necessary to have properly defined a primary key in the entity to determine whether a record +should be updated or created. + +Also the method executes associated validators, virtual foreign keys and events that are defined in the model: + +.. code-block:: php + + type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + if ($robot->save() == false) { + echo "Umh, We can't store robots right now: \n"; + foreach ($robot->getMessages() as $message) { + echo $message, "\n"; + } + } else { + echo "Great, a new robot was saved successfully!"; + } + +Create/Update with Certainty +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +When an application has a lot of competition, maybe we expect to create a record but that is actually updated. This could happen if we use +Phalcon\\Mvc\\Model::save() to persist the records in the database. If we want to be certain that a record will be created or updated +created we can change save by "create" or "update": + +.. code-block:: php + + type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + + //This record only must be created + if ($robot->create() == false) { + echo "Umh, We can't store robots right now: \n"; + foreach ($robot->getMessages() as $message) { + echo $message, "\n"; + } + } else { + echo "Great, a new robot was created successfully!"; + } + +Auto-generated identity columns +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Some models may have identity columns. These columns usually are the primary key of the mapped table. :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` +can recognize the identity column and will omit it from the internal SQL INSERT, so the database system could generate an auto-generated value for it. +Always after creating a record, the identity field will be registered with the value generated in the database system for it: + +.. code-block:: php + + save(); + echo "The generated id is: ", $robot->id; + +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` is able to recognize the identity column. Depending on the database system, those columns may be +serial columns like in PostgreSQL or auto_increment columns in the case of MySQL. + +PostgreSQL uses sequences to generate auto-numeric values, by default, Phalcon tries to obtain the generated value from the sequence "table_field_seq", +for example: robots_id_seq, if that sequence has a different name, the method "getSequenceName" needs to be implemented: + +.. code-block:: php + + ` has a messaging subsystem that provides a flexible way to output or store the +validation messages generated during the insert/update processes. + +Each message consists of an instance of the class :doc:`Phalcon\\Mvc\\Model\\Message <../api/Phalcon_Mvc_Model_Message>`. The set of +messages generated can be retrieved with the method getMessages(). Each message provides extended information like the field name that +generated the message or the message type: + +.. code-block:: php + + save() == false) { + foreach ($robot->getMessages() as $message) { + echo "Message: ", $message->getMessage(); + echo "Field: ", $message->getField(); + echo "Type: ", $message->getType(); + } + } + +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` can generate the following types of validation messages: + ++---------------------+------------------------------------------------------------------------------------------------------------------------------------+ +| Type | Description | ++=====================+====================================================================================================================================+ +| PresenceOf | Generated when a field with a non-null attribute on the database is trying to insert/update a null value | ++---------------------+------------------------------------------------------------------------------------------------------------------------------------+ +| ConstraintViolation | Generated when a field part of a virtual foreign key is trying to insert/update a value that doesn't exist in the referenced model | ++---------------------+------------------------------------------------------------------------------------------------------------------------------------+ +| InvalidValue | Generated when a validator failed due to an invalid value | ++---------------------+------------------------------------------------------------------------------------------------------------------------------------+ + +Validation Events and Events Manager +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Models allow you to implement events that will be thrown when performing an insert or update. They help to define business rules for a +certain model. The following are the events supported by :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` and their order of execution: + ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Operation | Name | Can stop operation? | Explanation | ++====================+==========================+=======================+=====================================================================================================================+ +| Inserting/Updating | beforeValidation | YES | Is executed before the fields are validated for not nulls or foreign keys | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | beforeValidationOnCreate | YES | Is executed before the fields are validated for not nulls or foreign keys when an insertion operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | beforeValidationOnUpdate | YES | Is executed before the fields are validated for not nulls or foreign keys when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | onValidationFails | YES (already stopped) | Is executed after an integrity validator fails | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | afterValidationOnCreate | YES | Is executed after the fields are validated for not nulls or foreign keys when an insertion operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | afterValidationOnUpdate | YES | Is executed after the fields are validated for not nulls or foreign keys when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | afterValidation | YES | Is executed after the fields are validated for not nulls or foreign keys | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | beforeSave | YES | Runs before the required operation over the database system | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | beforeUpdate | YES | Runs before the required operation over the database system only when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | beforeCreate | YES | Runs before the required operation over the database system only when an inserting operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | afterUpdate | NO | Runs after the required operation over the database system only when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | afterCreate | NO | Runs after the required operation over the database system only when an inserting operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | afterSave | NO | Runs after the required operation over the database system | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ + +To make a model to react to an event, we must to implement a method with the same name of the event: + +.. code-block:: php + + created_at = date('Y-m-d H:i:s'); + } + + public function beforeUpdate() + { + //Set the modification date + $this->modified_in = date('Y-m-d H:i:s'); + } + + } + +Additionally, this component is integrated with :doc:`Phalcon\\Events\\Manager <../api/Phalcon_Events_Manager>`, this means we can create +listeners that run when an event is triggered. + +.. code-block:: php + + attach('model', function($event, $robot) { + if ($event->getType() == 'beforeSave') { + if ($robot->name == 'Scooby Doo') { + echo "Scooby Doo isn't a robot!"; + return false; + } + } + return true; + }); + + $robot = new Robots(); + $robot->setEventsManager($eventsManager); + $robot->name = 'Scooby Doo'; + $robot->year = 1969; + $robot->save(); + +In the above example the EventsManager only acted as a bridge between an object and a listener (the anonymous function). If we want all +objects created in our application use the same EventsManager then we need to assign this to the Models Manager: + +.. code-block:: php + + set('modelsManager', function() { + + $eventsManager = new Phalcon\Events\Manager(); + + //Attach an anonymous function as a listener for "model" events + $eventsManager->attach('model', function($event, $model){ + if (get_class($model) == 'Robots') { + if ($event->getType() == 'beforeSave') { + if ($modle->name == 'Scooby Doo') { + echo "Scooby Doo isn't a robot!"; + return false; + } + } + } + return true; + }); + + //Setting a default EventsManager + $modelsManager = new Phalcon\Mvc\Models\Manager(); + $modelsManager->setEventsManager($eventsManager); + return $modelsManager; + }); + +Implementing a Business Rule +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +When an insert, update or delete is executed, the model verifies if there are any methods with the names of the events listed in the table above. + +We recommend that validation methods are declared protected to prevent that business logic implementation from being exposed publicly. + +The following example implements an event that validates the year cannot be smaller than 0 on update or insert: + +.. code-block:: php + + year < 0) { + echo "Year cannot be smaller than zero!"; + return false; + } + } + + } + +Some events return false as an indication to stop the current operation. If an event doesn't return anything, :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` +will assume a true value. + +Validating Data Integrity +^^^^^^^^^^^^^^^^^^^^^^^^^ +:doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` provides several events to validate data and implement business rules. The special "validation" +event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation. + +The following example shows how to use it: + +.. code-block:: php + + validate(new InclusionIn( + array( + "field" => "type", + "domain" => array("Mechanical", "Virtual") + ) + )); + + $this->validate(new Uniqueness( + array( + "field" => "name", + "message" => "The robot name must be unique" + ) + )); + + return $this->validationHasFailed() != true; + } + + } + +The above example performs a validation using the built-in validator "InclusionIn". It checks the value of the field "type" in a domain list. If +the value is not included in the method then the validator will fail and return false. The following built-in validators are available: + ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Name | Explanation | Example | ++==============+==================================================================================================================================================================+===================================================================+ +| PresenceOf | Validates that a field's value isn't null or empty string. This validator is automatically added based on the attributes marked as not null on the mapped table | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_PresenceOf>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Email | Validates that field contains a valid email format | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Email>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| ExclusionIn | Validates that a value is not within a list of possible values | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Exclusionin>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| InclusionIn | Validates that a value is within a list of possible values | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Inclusionin>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Numericality | Validates that a field has a numeric format | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Numericality>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Regex | Validates that the value of a field matches a regular expression | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Regex>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Uniqueness | Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Uniqueness>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| StringLength | Validates the length of a string | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_StringLength>` | ++--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ + +In addition to the built-in validatiors, you can create your own validators: + +.. code-block:: php + + getOption('field'); + + $value = $model->$field; + $filtered = filter_var($value, FILTER_VALIDATE_URL); + if (!$filtered) { + $this->appendMessage("The URL is invalid", $field, "UrlValidator"); + return false; + } + return true; + } + + } + +Adding the validator to a model: + +.. code-block:: php + + validate(new UrlValidator( + array( + "field" => "url", + ) + )); + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + +The idea of ​​creating validators is make them reusable between several models. A validator can also be as simple as: + +.. code-block:: php + + type == "Old") { + $message = new Phalcon\Mvc\Model\Message( + "Sorry, old robots are not allowed anymore", + "type", + "MyType" + ); + $this->appendMessage($message); + return false; + } + return true; + } + + } + +Avoiding SQL injections +^^^^^^^^^^^^^^^^^^^^^^^ +Every value assigned to a model attribute is escaped depending of its data type. A developer doesn't need to escape manually +each value before store it on the database. Phalcon uses internally the `bound parameters `_ +capability provided by PDO. + +.. code-block:: bash + + mysql> desc products; + +------------------+------------------+------+-----+---------+----------------+ + | Field | Type | Null | Key | Default | Extra | + +------------------+------------------+------+-----+---------+----------------+ + | id | int(10) unsigned | NO | PRI | NULL | auto_increment | + | product_types_id | int(10) unsigned | NO | MUL | NULL | | + | name | varchar(70) | NO | | NULL | | + | price | decimal(16,2) | NO | | NULL | | + | active | char(1) | YES | | NULL | | + +------------------+------------------+------+-----+---------+----------------+ + 5 rows in set (0.00 sec) + +If we use just PDO to store a record in a secure way, we need to write the following code: + +.. code-block:: php + + prepare($sql); + + $sth->bindParam(':productTypesId', $productTypesId, PDO::PARAM_INT); + $sth->bindParam(':name', $name, PDO::PARAM_STR, 70); + $sth->bindParam(':price', doubleval($price)); + $sth->bindParam(':active', $active, PDO::PARAM_STR, 1); + + $sth->execute(); + +The good news is that Phalcon do this automatically for you: + +.. code-block:: php + + product_types_id = 1; + $product->name = 'Artichoke'; + $product->price = 10.5; + $product->active = 'Y'; + $product->create(); + +Skipping Columns +---------------- +To tell to Phalcon\\Mvc\\Model that omits some fields in the creation and/or update in order to delegate the database +system assigns the value by a trigger or a default: + +.. code-block:: php + + skipAttributes(array('year', 'price')); + + //Skips only when inserting + $this->skipAttributesOnCreate(array('created_at')); + + //Skips only when updating + $this->skipAttributesOnUpdate(array('modified_in')); + } + + } + +This will ignore globally these fields on each INSERT/UPDATE operation on the whole application. +Forcing a default value can be done in the following way: + +.. code-block:: php + + name = 'Bender'; + $robot->year = 1999; + $robot->created_at = new Phalcon\Db\RawValue('default'); + $robot->create(); + +Deleting Records +---------------- +The method Phalcon\\Mvc\\Model::delete() allows to delete a record. You can use it as follows: + +.. code-block:: php + + delete() == false) { + echo "Sorry, we can't delete the robot right now: \n"; + foreach ($robot->getMessages() as $message) { + echo $message, "\n"; + } + } else { + echo "The robot was deleted successfully!"; + } + } + +You can also delete many records by traversing a resultset with a foreach: + +.. code-block:: php + + delete() == false) { + echo "Sorry, we can't delete the robot right now: \n"; + foreach ($robot->getMessages() as $message) { + echo $message, "\n"; + } + } else { + echo "The robot was deleted successfully!"; + } + } + +The following events are available to define custom business rules that can be executed when a delete operation is performed: + ++-----------+--------------+---------------------+------------------------------------------+ +| Operation | Name | Can stop operation? | Explanation | ++===========+==============+=====================+==========================================+ +| Deleting | beforeDelete | YES | Runs before the delete operation is made | ++-----------+--------------+---------------------+------------------------------------------+ +| Deleting | afterDelete | NO | Runs after the delete operation was made | ++-----------+--------------+---------------------+------------------------------------------+ + +Validation Failed Events +------------------------ + +Another type of events is available when the data validation process finds any inconsistency: + ++--------------------------+--------------------+--------------------------------------------------------------------+ +| Operation | Name | Explanation | ++==========================+====================+====================================================================+ +| Insert or Update | notSave | Triggered when the INSERT or UPDATE operation fails for any reason | ++--------------------------+--------------------+--------------------------------------------------------------------+ +| Insert, Delete or Update | onValidationFails | Triggered when any data manipulation operation fails | ++--------------------------+--------------------+--------------------------------------------------------------------+ + +Transactions +------------ +When a process performs multiple database operations, it is often that each step is completed successfully so that data integrity can +be maintained. Transactions offer the ability to ensure that all database operations have been executed successfully before the data +is committed in the database. + +Transactions in Phalcon allow you to commit all operations if they have been executed successfully or rollback all operations if something went wrong. + +.. code-block:: php + + get(); + + $robot = new Robots(); + $robot->setTransaction($transaction); + $robot->name = "WALL·E"; + $robot->created_at = date("Y-m-d"); + if ($robot->save() == false) { + $transaction->rollback("Cannot save robot"); + } + + $robotPart = new RobotParts(); + $robotPart->setTransaction($transaction); + $robotPart->type = "head"; + if ($robotPart->save() == false) { + $transaction->rollback("Cannot save robot part"); + } + + //Everything goes fine, let's commit the transaction + $transaction->commit(); + + } catch(Phalcon\Mvc\Model\Transaction\Failed $e) { + echo "Failed, reason: ", $e->getMessage(); + } + +Transactions can be used to delete many records in a consistent way: + +.. code-block:: php + + get(); + + //Get the robots will be deleted + foreach (Robots::find("type='mechanical'") as $robot) { + $robot->setTransaction($transaction); + if ($robot->delete() == false) { + //Something goes wrong, we should to rollback the transaction + foreach ($robot->getMessages() as $message) { + $transaction->rollback($message->getMessage()); + } + } + } + + //Everything goes fine, let's commit the transaction + $transaction->commit(); + + echo "Robots were deleted successfully!"; + + } catch(Phalcon\Mvc\Model\Transaction\Failed $e) { + echo "Failed, reason: ", $e->getMessage(); + } + +Transactions are reused no matter where the transaction object is retrieved. A new transaction is generated only when a commit() or rollback() +is performed. You can use the service container to create an overall transaction manager for the entire application: + +.. code-block:: php + + set('transactions', function(){ + return new Phalcon\Mvc\Model\Transaction\Manager(); + }); + +Then access it from a controller or view: + +.. code-block:: php + + di->getShared('transactions'); + + //Request a transaction + $transaction = $manager->get(); + + } + + } + +Models Meta-Data +---------------- +To speed up development :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` helps you to query fields and constraints from tables +related to models. To achieve this, :doc:`Phalcon\\Mvc\\Model\\MetaData <../api/Phalcon_Mvc_Model_MetaData>` is available to manage +and cache table meta-data. + +Sometimes it is necessary to get those attributes when working with models. You can get a meta-data instance as follows: + +.. code-block:: php + + getDI()->getModelsMetaData(); + + // Get robots fields names + $attributes = $metaData->getAttributes($robot); + print_r($attributes); + + // Get robots fields data types + $dataTypes = $metaData->getDataTypes($robot); + print_r($dataTypes); + +Caching Meta-Data +^^^^^^^^^^^^^^^^^ +Once the application is in a production stage, it is not necessary to query the meta-data of the table from the database system each +time you use the table. This could be done caching the meta-data using any of the following adapters: + ++---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------+ +| Adapter | Description | API | ++=========+===============================================================================================================================================================================================================================================================================================================================================+===========================================================================================+ +| Memory | This adapter is the default. The meta-data is cached only during the request. When the request is completed, the meta-data are released as part of the normal memory of the request. This adapter is perfect when the application is in development so as to refresh the meta-data in each request containing the new and/or modified fields. | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Memory <../api/Phalcon_Mvc_Model_MetaData_Memory>` | ++---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------+ +| Session | This adapter stores meta-data in the $_SESSION superglobal. This adapter is recommended only when the application is actually using a small number of models. The meta-data are refreshed every time a new session starts. This also requires the use of session_start() to start the session before using any models. | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Session <../api/Phalcon_Mvc_Model_MetaData_Session>` | ++---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------+ +| Apc | The Apc adapter uses the `Alternative PHP Cache (APC)`_ to store the table meta-data. You can specify the lifetime of the meta-data with options. This is the most recommended way to store meta-data when the application is in production stage. | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Apc <../api/Phalcon_Mvc_Model_MetaData_Apc>` | ++---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------+ +| Files | This adapter uses plain files to store meta-data. By using this adapter the disk-reading is increased but the database access is reduced | :doc:`Phalcon\\Mvc\\Model\\MetaData\\Files <../api/Phalcon_Mvc_Model_MetaData_Files>` | ++---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------------------+ + +As other ORM's dependencies, the metadata manager is requested from the services container: + +.. code-block:: php + + set('modelsMetadata', function() { + + // Create a meta-data manager with APC + $metaData = new Phalcon\Mvc\Model\MetaData\Apc( + array( + "lifetime" => 86400, + "suffix" => "my-suffix" + ) + ); + + return $metaData; + }); + +Manual Meta-Data +^^^^^^^^^^^^^^^^ +Phalcon can obtain the metadata for each model automatically without the developer must set them manually. +Remember that when defining the metadata manually, new columns added/modified/removed to/from the mapped +table must be added/modified/removed also for everything to work correctly. + +The following example shows how to define the meta-data manually: + +.. code-block:: php + + array( + 'id', 'name', 'type', 'year' + ), + + //Every column part of the primary key + MetaData::MODELS_PRIMARY_KEY => array( + 'id' + ), + + //Every column that isn't part of the primary key + MetaData::MODELS_NON_PRIMARY_KEY => array( + 'name', 'type', 'year' + ), + + //Every column that doesn't allows null values + MetaData::MODELS_NOT_NULL => array( + 'id', 'name', 'type', 'year' + ), + + //Every column and their data types + MetaData::MODELS_DATA_TYPES => array( + 'id' => Column::TYPE_INTEGER, + 'name' => Column::TYPE_VARCHAR, + 'type' => Column::TYPE_VARCHAR, + 'year' => Column::TYPE_INTEGER + ), + + //The columns that have numeric data types + MetaData::MODELS_DATA_TYPES_NUMERIC => array( + 'id' => true, + 'year' => true, + ), + + //The identity column + MetaData::MODELS_IDENTITY_COLUMN => 'id', + + //How every column must be binded/casted + MetaData::MODELS_DATA_TYPES_BIND => array( + 'id' => Column::BIND_PARAM_INT, + 'name' => Column::BIND_PARAM_STR, + 'type' => Column::BIND_PARAM_STR, + 'year' => Column::BIND_PARAM_INT, + ), + + //Fields that must be ignored from INSERT/UPDATE SQL statements + MetaData::MODELS_AUTOMATIC_DEFAULT => array('year') + + ); + } + + } + +Setting a different schema +-------------------------- +Models may are mapped to tables that are in different schemas/databases than the default. You can use the getSchema method to define that: + +Then, in the Initialize method, we define the connection service for the model: + +.. code-block:: php + + ` needs to connect to the database it requests the "db" service +in the application's services container. You can overwrite this service setting it in the initialize method: + +.. code-block:: php + + set('dbMysql', function() { + return new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + }); + + //This service returns a PostgreSQL database + $di->set('dbPostgres', function() { + return new \Phalcon\Db\Adapter\Pdo\PostgreSQL(array( + "host" => "localhost", + "username" => "postgres", + "password" => "", + "dbname" => "invo" + )); + }); + +Then, in the Initialize method, we define the connection service for the model: + +.. code-block:: php + + setConnectionService('dbPostgres'); + } + + } + +Logging Low-Level SQL Statements +-------------------------------- +When using high-level abstraction components such as :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` to access a database, it is +difficult to understand which statements are finally sent to the database system. :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>` +is supported internally by :doc:`Phalcon\\Db <../api/Phalcon_Db>`. :doc:`Phalcon\\Logger <../api/Phalcon_Logger>` interacts +with :doc:`Phalcon\\Db <../api/Phalcon_Db>`, providing logging capabilities on the database abstraction layer, thus allowing us to log SQL +statements as they happen. + +.. code-block:: php + + set('db', function() { + + $eventsManager = new Phalcon\Events\Manager(); + + $logger = new Phalcon\Logger\Adapter\File("app/logs/debug.log"); + + //Listen all the database events + $eventsManager->attach('db', function($event, $connection) use ($logger) { + if ($event->getType() == 'beforeQuery') { + $logger->log($connection->getSQLStatement(), \Phalcon\Logger::INFO); + } + }); + + $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + + //Assign the eventsManager to the db adapter instance + $connection->setEventsManager($eventsManager); + + return $connection; + }); + +As models access the default database connection, all SQL statements that are sent to the database system will be logged in the file: + +.. code-block:: php + + name = "Robby the Robot"; + $robot->created_at = "1956-07-21" + if ($robot->save() == false) { + echo "Cannot save robot"; + } + +As above, the file *app/logs/db.log* will contain something like this: + +.. code-block:: irc + + [Mon, 30 Apr 12 13:47:18 -0500][DEBUG][Resource Id #77] INSERT INTO robots + (name, created_at) VALUES ('Robby the Robot', '1956-07-21') + +Profiling SQL Statements +------------------------ +Thanks to :doc:`Phalcon\\Db <../api/Phalcon_Db>`, the underlying component of :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>`, +it's possible to profile the SQL statements generated by the ORM in order to analyze the performance of database operations. With +this you can diagnose performance problems and to discover bottlenecks. + +.. code-block:: php + + set('profiler', function(){ + return new Phalcon\Db\Profiler(); + }) + + $di->set('db', function() use($di) { + + $eventsManager = new Phalcon\Events\Manager(); + + //Get a shared instance of the DbProfiler + $profiler = $di->getShared('profiler'); + + //Listen all the database events + $eventsManager->attach('db', function($event, $connection) use ($profiler) { + if ($event->getType() == 'beforeQuery') { + $profiler->startProfile($connection->getSQLStatement()); + } + if ($event->getType() == 'afterQuery') { + $profiler->stopProfile(); + } + }); + + $connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "invo" + )); + + //Assign the eventsManager to the db adapter instance + $connection->setEventsManager($eventsManager); + + return $connection; + }); + +Profiling some queries: + +.. code-block:: php + + "name"); + Robots::find(array("limit" => 30); + + //Get the generated profiles from the profiler + $profiles = $di->getShared('profiler')->getProfiles(); + + foreach ($profiles as $profile) { + echo "SQL Statement: ", $profile->getSQLStatement(), "\n"; + echo "Start Time: ", $profile->getInitialTime(), "\n"; + echo "Final Time: ", $profile->getFinalTime(), "\n"; + echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n"; + } + +Each generated profile contains the duration in miliseconds that each instruction takes to complete as well as the generated SQL statement. + +Injecting services into Models +------------------------------ +You may be required to access the application services within a model, the following example explains how to do that: + +.. code-block:: php + + getDI()->getShared('flash'); + + //Show validation messages + foreach($this->getMesages() as $message) { + $flash->error((string) $message); + } + } + + } + +The "notSave" event is triggered every time that a "create" or "update" action fails. So we're flashing the validation messages +obtaining the "flash" service from the DI container. By doing this, we don't have to print messages after each save. + + +.. _Alternative PHP Cache (APC): http://www.php.net/manual/en/book.apc.php +.. _PDO: http://www.php.net/manual/en/pdo.prepared-statements.php diff --git a/zh/reference/motivation.rst b/zh/reference/motivation.rst new file mode 100755 index 000000000000..fa0003fef2fe --- /dev/null +++ b/zh/reference/motivation.rst @@ -0,0 +1,59 @@ +我们的目的 +========== + +现在有很多各种各样的PHP框架,但他们没有一个像Phalcon一样(真的,在这点上请相信我) + +几乎所有的程序员都喜欢使用框架,这主要是因为框架提供了很多的功能,已经经过了大量的测试,因此保持代码DRY(不要重复造轮子)。然而,框架本身需要包含大量的文件来解释和执行实际应用中的每个请求,因此会降低应用程序的性能,影响用户体验。 + +The Question +------------ + +为什么我们不能有这样一个框架,保持它的优势的同时,没有或者很少有缺点呢? + +这就是为什么Phalcon诞生了! + +在过去的几个月中,我们已经广泛地研究了PHP的行为,调查区域为显着优化(大或小)。 +通过Zend引擎的理解,我们设法消除不必要的验证,压缩的代码,进行优化和生成的 +低级别的解决方案,从而使Phalcon实现最大的性能。 + +Why? +---- + +* The use of frameworks has become mandatory in professional development with PHP +* 框架提供了结构化的理念,以轻松维护项目,编写更少的代码,使工作变得更有趣 + +Inner workings of PHP? +---------------------- + +* PHP是一种动态的和弱变量类型语言。每次一个二进制运算(例如,2+“2”),PHP就会检查操作数的类型来进行类型转换 +* PHP是解释型语言。主要的缺点是性能上的损失 +* 每一个请求,它必须首先解释. +* 如果不使用字节码缓存(如APC),则任何时间的任何一个请求它都会进行语法检查 + +How traditional PHP frameworks work? +------------------------------------ + +* Many files with classes and functions are read on every request made. Disk reading is expensive in terms of performance, especially when the file structure includes deep folders +* Modern frameworks use lazy loading (autoload) to increase performance (for load and execute only the code needed) +* Continuous loading or interpreting is expensive and impacts performance +* The framework code does not change very often, therefore an application needs to load and interpret it every time a request is made + +How does a PHP C-extension work? +-------------------------------- + +* C extensions are loaded together with PHP one time on the web server's daemon start process +* Classes and functions provided by the extension are ready to use for any application +* The code isn't interpreted because is already compiled to a specific platform and processor + +How does Phalcon work? +---------------------- + +* Components are loosely coupled. With Phalcon, nothing is imposed on you: you're free to use the full framework, or just some parts of it as a glue components. +* Low-level optimizations provides the lowest overhead for MVC-based applications +* Interact with databases with maximum performance by using a C-language ORM for PHP +* Phalcon directly accesses internal PHP structures optimizing execution in that way as well + +Conclusion +---------- +Phalcon is an effort to build the fastest framework for PHP. You now have an even easier and robust way to develop applications without be worrying about performance. Enjoy! + diff --git a/zh/reference/mvc.rst b/zh/reference/mvc.rst new file mode 100755 index 000000000000..bb0b827c6067 --- /dev/null +++ b/zh/reference/mvc.rst @@ -0,0 +1,25 @@ +The MVC Architecture +==================== + +Phalcon offers the object-oriented classes, necessary to implement the Model, View, Controller architecture (often referred to as MVC_) in your application. This design pattern is widely used by other web frameworks and desktop applications. + +MVC benefits include: + +* Isolation of business logic from the user interface and the database layer +* Making it clear where different types of code belong for easier maintenance + +If you decide to use MVC, every request to your application resources will be managed by the MVC_ architecture. Phalcon classes are written in C language, offering a high performance approach of this pattern in a PHP based application. + +Models +------ +A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models. :doc:`Learn more ` + +Views +----- +Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. :doc:`Learn more ` + +Controllers +----------- +The controllers provide the "flow" between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation. :doc:`Learn more ` + +.. _MVC: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller diff --git a/zh/reference/namespaces.rst b/zh/reference/namespaces.rst new file mode 100644 index 000000000000..a9fce69863e2 --- /dev/null +++ b/zh/reference/namespaces.rst @@ -0,0 +1,125 @@ +Working with Namespaces +======================= +Namespaces_ can be used to avoid class name collisions; this means that if you have two controllers in an application with the same name, +it's possible use a namespace to differentiate them. Namespaces are also useful for creating bundles or modules. + +Setting up the framework +------------------------ +Using namespaces has some implications when loading the appropriate controller. To adjust the framework behavior to namespaces is necessary +to perform one or all of the following tasks: + +Use an autoload strategy that takes into account the namespaces, for example with Phalcon\\Loader: + +.. code-block:: php + + registerNamespaces( + array( + 'Store\Admin\Controllers' => "../bundles/admin/controllers/", + 'Store\Admin\Models' => "../bundles/admin/models/", + ) + ); + +Specify in the routes a full class name in the controller path: + +.. code-block:: php + + add( + "/admin/users/my-profile", + array( + "controller" => "Store\Admin\Users", + "action" => "profile", + ) + ); + +If you are only working with the same namespace for every controller in your application, then you can define a default namespace +in the Dispatcher. by doing this you don't need to specify a full class name in the router path. + +.. code-block:: php + + set('dispatcher', function() { + $dispatcher = new \Phalcon\Mvc\Dispatcher(); + $dispatcher->setDefaultNamespace('Store\Admin\Controllers\\'); + return $dispatcher; + }); + +Controllers with Namespaces +--------------------------- +The following example shows how to implement a controller that use namespaces: + +.. code-block:: php + + hasMany("id", 'Store\Toys\RobotsParts', 'robots_id'); + } + + public function getRobotsParts($arguments=null) + { + return $this->getRelated('Store\Toys\RobotsParts', $arguments); + } + + } + +.. _Namespaces: http://php.net/manual/en/language.namespaces.php \ No newline at end of file diff --git a/zh/reference/nginx.rst b/zh/reference/nginx.rst new file mode 100755 index 000000000000..396a2d0c0aea --- /dev/null +++ b/zh/reference/nginx.rst @@ -0,0 +1,108 @@ +Nginx Installation Notes +======================== +Nginx_ is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server. Unlike +traditional servers, Nginx_ doesn't rely on threads to handle requests. Instead it uses a much more scalable event-driven +(asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load. + +The `PHP-FPM`_ (FastCGI Process Manager) is usually used to allow Nginx_ to process PHP files. Nowadays, `PHP-FPM`_ is +bundled with any Unix PHP distribution. Phalcon + Nginx_ + `PHP-FPM`_ provides a powerful set of tools that offer +maximum performance for your PHP applications. + +Configuring Nginx for Phalcon +----------------------------- +The following are potential configurations you can use to setup nginx with Phalcon. + +Dedicated Instance +^^^^^^^^^^^^^^^^^^ + +.. code-block:: nginx + + server { + listen 80; + server_name localhost; + + charset utf-8; + + #access_log /var/log/nginx/host.access.log main; + + location / { + root /srv/www/htdocs/phalcon-website/public; + index index.php index.html index.htm; + + # if file exists return it right away + if (-f $request_filename) { + break; + } + + # otherwise rewrite it + if (!-e $request_filename) { + rewrite ^(.+)$ /index.php?_url=$1 last; + break; + } + } + + location ~ \.php { + # try_files $uri =404; + + fastcgi_index /index.php; + fastcgi_pass 127.0.0.1:9000; + + include fastcgi_params; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + } + + location ~* ^/(css|img|js|flv|swf|download)/(.+)$ { + root $root_path; + } + } + +Configuration by Host +^^^^^^^^^^^^^^^^^^^^^ +And this second configuration allow you to have different configurations by host: + +.. code-block:: nginx + + server { + listen 80; + server_name localhost; + set $root_path '/var/www/$host/public'; + root $root_path; + + access_log /var/log/nginx/$host-access.log; + error_log /var/log/nginx/$host-error.log error; + + index index.php index.html index.htm; + + try_files $uri $uri/ @rewrite; + + location @rewrite { + rewrite ^/(.*)$ /index.php?_url=$1; + } + + location ~ \.php { + # try_files $uri =404; + + fastcgi_index /index.php; + fastcgi_pass 127.0.0.1:9000; + + include fastcgi_params; + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + } + + location ~* ^/(css|img|js|flv|swf|download)/(.+)$ { + root $root_path; + } + + location ~ /\.ht { + deny all; + } + } + +.. _Nginx: http://wiki.nginx.org/Main +.. _PHP-FPM: http://php-fpm.org/ diff --git a/zh/reference/odm.rst b/zh/reference/odm.rst new file mode 100644 index 000000000000..3916b2c94b2b --- /dev/null +++ b/zh/reference/odm.rst @@ -0,0 +1,770 @@ +ODM (Object-Document Mapper) +============================ +In addition to its ability to :doc:`map tables ` in relational databases, Phalcon can map documents from NoSQL databases. +The ODM offers a CRUD functionality, events, validations among other services. + +Due to the absence of SQL queries and planners, NoSQL databases can see real improvements in performance using the Phalcon approach. +Additionally, there are no SQL building eliminating the possibility of SQL injections. + +The following NoSQL databases are supported: + ++------------+----------------------------------------------------------------------+ +| Name | Description | ++============+======================================================================+ +| MongoDB_ | MongoDB is a scalable, high-performance, open source NoSQL database. | ++------------+----------------------------------------------------------------------+ + +Creating Models +--------------- +A model is a class that extends from :doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>`. It must be placed in the models directory. A model +file must contain a single class; its class name should be in camel case notation: + +.. code-block:: php + + db.robots.find() + { "_id" : ObjectId("508735512d42b8c3d15ec4e1"), "name" : "Astro Boy", "year" : 1952, + "type" : "mechanical" } + { "_id" : ObjectId("5087358f2d42b8c3d15ec4e2"), "name" : "Bender", "year" : 1999, + "type" : "mechanical" } + { "_id" : ObjectId("508735d32d42b8c3d15ec4e3"), "name" : "Wall-E", "year" : 2008 } + > + +Models in Namespaces +-------------------- +Namespaces can be used to avoid class name collision. In this case it is necessary to indicate the name of the related collection using getSource: + +.. code-block:: php + + name; + +Once the record is in memory, you can make modifications to its data and then save changes: + +.. code-block:: php + + 'Astroy Boy') + ) + ); + $robot->name = "Voltron"; + $robot->save(); + +Setting a Connection +-------------------- +Connections are retrieved from the services container. By default, Phalcon tries to find the connection in a service called "mongo": + +.. code-block:: php + + set( + 'mongo', + function() + { + $mongo = new Mongo(); + return $mongo->selectDb("store"); + } + ); + + // Connecting to a domain socket, falling back to localhost connection + $di->set( + 'mongo', + function() + { + $mongo = new Mongo("mongodb:///tmp/mongodb-27017.sock,localhost:27017"); + return $mongo->selectDb("store"); + } + ); + +Finding Documents +----------------- +As :doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>` relies on the Mongo PHP extension you have the same facilities +to query documents and convert them transparently to model instances: + +.. code-block:: php + + "mechanical") + ) + ); + echo "There are ", count($robots), "\n"; + + // Get and print mechanical robots ordered by name upward + $robots = Robots::find( + array( + array("type" => "mechanical"), + "sort" => array("name" => 1) + ) + ); + + foreach ($robots as $robot) + { + echo $robot->name, "\n"; + } + + // Get first 100 mechanical robots ordered by name + $robots = Robots::find( + array( + array("type" => "mechanical"), + "sort" => array("name" => 1), + "limit" => 100 + ) + ); + + foreach ($robots as $robot) + { + echo $robot->name, "\n"; + } + +You could also use the findFirst() method to get only the first record matching the given criteria: + +.. code-block:: php + + name, "\n"; + + // What's the first mechanical robot in robots collection? + $robot = Robots::findFirst( + array( + array("type" => "mechanical") + ) + ); + echo "The first mechanical robot name is ", $robot->name, "\n"; + +Both find() and findFirst() methods accept an associative array specifying the search criteria: + +.. code-block:: php + + "mechanical", + "year" => "1999" + ) + ); + + // All virtual robots ordered by name downward + $robots = Robots::find( + array( + "conditions" => array("type" => "virtual"), + "sort" => array("name" => -1) + ) + ); + +The available query options are: + ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| Parameter | Description | Example | ++=============+==============================================================================================================================================================================================+=========================================================================+ +| conditions | Search conditions for the find operation. Is used to extract only those records that fulfill a specified criterion. By default Phalcon_model assumes the first parameter are the conditions. | "conditions" => array('$gt' => 1990) | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| sort | Is used to sort the resultset. Use one or more fields as each element in the array, 1 means ordering upwards, -1 downward | "order" => array("name" => -1, "statys" => 1) | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| limit | Limit the results of the query to results to certain range | "limit" => 10 | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ +| skip | Skips a number of results | "skip" => 50 | ++-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------+ + +If you have experience with SQL databases, you may want to check the `SQL to Mongo Mapping Chart`_. + +Creating Updating/Records +------------------------- +The method Phalcon\\Mvc\\Collection::save() allows you to create/update documents according to whether they already exist in the collection +associated with a model. The save method is called internally by the create and update methods of :doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>`. + +Also the method executes associated validators and events that are defined in the model: + +.. code-block:: php + + type = "mechanical"; + $robot->name = "Astro Boy"; + $robot->year = 1952; + if ($robot->save() == false) + { + echo "Umh, We can't store robots right now: \n"; + foreach ($robot->getMessages() as $message) + { + echo $message, "\n"; + } + } + else + { + echo "Great, a new robot was saved successfully!"; + } + +The "_id" property is automatically updated with the MongoId_ object created by the driver: + +.. code-block:: php + + save(); + echo "The generated id is: ", $robot->getId(); + +Validation Messages +^^^^^^^^^^^^^^^^^^^ +:doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>` has a messaging subsystem that provides a flexible way to output or store the +validation messages generated during the insert/update processes. + +Each message consists of an instance of the class :doc:`Phalcon\\Mvc\\Model\\Message <../api/Phalcon_Mvc_Model_Message>`. The set of +messages generated can be retrieved with the method getMessages(). Each message provides extended information like the field name that +generated the message or the message type: + +.. code-block:: php + + save() == false) + { + foreach ($robot->getMessages() as $message) + { + echo "Message: ", $message->getMessage(); + echo "Field: ", $message->getField(); + echo "Type: ", $message->getType(); + } + } + +Validation Events and Events Manager +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Models allow you to implement events that will be thrown when performing an insert or update. They help to define business rules for a +certain model. The following are the events supported by :doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>` and their order of execution: + ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Operation | Name | Can stop operation? | Explanation | ++====================+==========================+=======================+=====================================================================================================================+ +| Inserting/Updating | beforeValidation | YES | Is executed before the validation process and the final insert/update to the database | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | beforeValidationOnCreate | YES | Is executed before the validation process only when an insertion operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | beforeValidationOnUpdate | YES | Is executed before the fields are validated for not nulls or foreign keys when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | onValidationFails | YES (already stopped) | Is executed before the validation process only when an insertion operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | afterValidationOnCreate | YES | Is executed after the validation process when an insertion operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | afterValidationOnUpdate | YES | Is executed after the validation process when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | afterValidation | YES | Is executed after the validation process | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | beforeSave | YES | Runs before the required operation over the database system | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | beforeUpdate | YES | Runs before the required operation over the database system only when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | beforeCreate | YES | Runs before the required operation over the database system only when an inserting operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Updating | afterUpdate | NO | Runs after the required operation over the database system only when an updating operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting | afterCreate | NO | Runs after the required operation over the database system only when an inserting operation is being made | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ +| Inserting/Updating | afterSave | NO | Runs after the required operation over the database system | ++--------------------+--------------------------+-----------------------+---------------------------------------------------------------------------------------------------------------------+ + +To make a model to react to an event, we must to implement a method with the same name of the event: + +.. code-block:: php + + created_at = date('Y-m-d H:i:s'); + } + + public function beforeUpdate() + { + // Set the modification date + $this->modified_in = date('Y-m-d H:i:s'); + } + + } + +Additionally, this component is integrated with :doc:`Phalcon\\Events\\Manager `, this means we can create +listeners that run when an event is triggered. + +.. code-block:: php + + attach( + 'model', + function($event, $robot) + { + if ($event->getType() == 'beforeSave') + { + if ($robot->name == 'Scooby Doo') + { + echo "Scooby Doo isn't a robot!"; + return false; + } + } + return true; + } + ); + + $robot = new Robots(); + $robot->setEventsManager($eventsManager); + $robot->name = 'Scooby Doo'; + $robot->year = 1969; + $robot->save(); + +In the above example the EventsManager only acted as a bridge between an object and a listener (the anonymous function). If we want all +objects created in our application use the same EventsManager then we need to assign this to the Models Manager: + +.. code-block:: php + + set( + 'collectionManager', + function() + { + $eventsManager = new Phalcon\Events\Manager(); + + // Attach an anonymous function as a listener for "model" events + $eventsManager->attach( + 'model', + function($event, $model) + { + if (get_class($model) == 'Robots') + { + if ($event->getType() == 'beforeSave') + { + if ($model->name == 'Scooby Doo') + { + echo "Scooby Doo isn't a robot!"; + return false; + } + } + } + return true; + } + ); + + // Setting a default EventsManager + $modelsManager = new Phalcon\Mvc\Collection\Manager(); + $modelsManager->setEventsManager($eventsManager); + return $modelsManager; + } + ); + +Implementing a Business Rule +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +When an insert, update or delete is executed, the model verifies if there are any methods with the names of the events listed in the table above. + +We recommend that validation methods are declared protected to prevent that business logic implementation from being exposed publicly. + +The following example implements an event that validates the year cannot be smaller than 0 on update or insert: + +.. code-block:: php + + year < 0) + { + echo "Year cannot be smaller than zero!"; + return false; + } + } + + } + +Some events return false as an indication to stop the current operation. If an event doesn't return anything, +:doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>` will assume a true value. + +Validating Data Integrity +^^^^^^^^^^^^^^^^^^^^^^^^^ +:doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>` provides several events to validate data and implement business rules. The special "validation" +event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation. + +The following example shows how to use it: + +.. code-block:: php + + validate(new InclusionIn( + array( + "field" => "type", + "domain" => array("Mechanical", "Virtual") + ) + )); + + $this->validate(new Uniqueness( + array( + "field" => "name", + "message" => "The robot name must be unique" + ) + )); + + return $this->validationHasFailed() != true; + } + + } + +The above example performs a validation using the built-in validator "InclusionIn". It checks the value of the field "type" in a domain list. If +the value is not included in the method then the validator will fail and return false. The following built-in validators are available: + ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Name | Explanation | Example | ++==============+========================================================================================================================================+===================================================================+ +| Email | Validates that field contains a valid email format | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Email>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| ExclusionIn | Validates that a value is not within a list of possible values | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Exclusionin>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| InclusionIn | Validates that a value is within a list of possible values | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Inclusionin>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Numericality | Validates that a field has a numeric format | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Numericality>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Regex | Validates that the value of a field matches a regular expression | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Regex>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| Uniqueness | Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_Uniqueness>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ +| StringLength | Validates the length of a string | :doc:`Example <../api/Phalcon_Mvc_Model_Validator_StringLength>` | ++--------------+----------------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------+ + +In addition to the built-in validatiors, you can create your own validators: + +.. code-block:: php + + getOption('field'); + + $value = $model->$field; + $filtered = filter_var($value, FILTER_VALIDATE_URL); + if (!$filtered) + { + $this->appendMessage("The URL is invalid", $field, "UrlValidator"); + return false; + } + return true; + } + + } + +Adding the validator to a model: + +.. code-block:: php + + validate(new UrlValidator( + array( + "field" => "url", + ) + )); + if ($this->validationHasFailed() == true) + { + return false; + } + } + + } + +The idea of ​​creating validators is make them reusable between several models. A validator can also be as simple as: + +.. code-block:: php + + type == "Old") + { + $message = new Phalcon\Mvc\Model\Message( + "Sorry, old robots are not allowed anymore", + "type", + "MyType" + ); + $this->appendMessage($message); + return false; + } + return true; + } + + } + +Deleting Records +---------------- +The method Phalcon\\Mvc\\Collection::delete() allows to delete a document. You can use it as follows: + +.. code-block:: php + + delete() == false) + { + echo "Sorry, we can't delete the robot right now: \n"; + foreach ($robot->getMessages() as $message) + { + echo $message, "\n"; + } + } + else + { + echo "The robot was deleted successfully!"; + } + } + +You can also delete many documents by traversing a resultset with a foreach: + +.. code-block:: php + + "mechanical" + ) + ); + foreach ($robots as $robot) + { + if ($robot->delete() == false) + { + echo "Sorry, we can't delete the robot right now: \n"; + foreach ($robot->getMessages() as $message) + { + echo $message, "\n"; + } + } + else + { + echo "The robot was deleted successfully!"; + } + } + +The following events are available to define custom business rules that can be executed when a delete operation is performed: + ++-----------+--------------+---------------------+------------------------------------------+ +| Operation | Name | Can stop operation? | Explanation | ++===========+==============+=====================+==========================================+ +| Deleting | beforeDelete | YES | Runs before the delete operation is made | ++-----------+--------------+---------------------+------------------------------------------+ +| Deleting | afterDelete | NO | Runs after the delete operation was made | ++-----------+--------------+---------------------+------------------------------------------+ + +Validation Failed Events +------------------------ + +Another type of events is available when the data validation process finds any inconsistency: + ++--------------------------+--------------------+--------------------------------------------------------------------+ +| Operation | Name | Explanation | ++==========================+====================+====================================================================+ +| Insert or Update | notSave | Triggered when the insert/update operation fails for any reason | ++--------------------------+--------------------+--------------------------------------------------------------------+ +| Insert, Delete or Update | onValidationFails | Triggered when any data manipulation operation fails | ++--------------------------+--------------------+--------------------------------------------------------------------+ + +Setting multiple databases +-------------------------- +In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when +:doc:`Phalcon\\Mvc\\Collection <../api/Phalcon_Mvc_Collection>` needs to connect to the database it requests the "mongo" service +in the application's services container. You can overwrite this service setting it in the initialize method: + +.. code-block:: php + + set( + 'mongo1', + function() + { + $mongo = new Mongo("mongodb://scott:nekhen@192.168.1.100"); + return $mongo->selectDb("management"); + } + ); + + // This service returns a mongo database at localhost + $di->set( + 'mongo2', + function() + { + $mongo = new Mongo("mongodb://localhost"); + return $mongo->selectDb("invoicing"); + } + ); + +Then, in the Initialize method, we define the connection service for the model: + +.. code-block:: php + + setConnectionService('mongo1'); + } + + } + +Injecting services into Models +------------------------------ +You may be required to access the application services within a model, the following example explains how to do that: + +.. code-block:: php + + getDI()->getShared('flash'); + + // Show validation messages + foreach($this->getMesages() as $message) + { + $flash->error((string) $message); + } + } + + } + +The "notSave" event is triggered every time that a "create" or "update" action fails. So we're flashing the validation messages +obtaining the "flash" service from the DI container. By doing this, we don't have to print messages after each save. + +.. _MongoDB: http://www.mongodb.org/ +.. _MongoId: http://www.php.net/manual/en/class.mongoid.php +.. _`SQL to Mongo Mapping Chart`: http://www.php.net/manual/en/mongo.sqltomongo.php \ No newline at end of file diff --git a/zh/reference/pagination.rst b/zh/reference/pagination.rst new file mode 100755 index 000000000000..c54598f4c51a --- /dev/null +++ b/zh/reference/pagination.rst @@ -0,0 +1,92 @@ +Data Pagination +=============== +The process of pagination takes place when we need to present big groups of arbitrary data gradually. Phalcon\\Paginator offers a +fast and convenient way to split these sets of data browsable pages. + +Data Adapters +------------- +This component makes use of adapters to encapsulate different sources of data: + ++--------------+-------------------------------------------------------+ +| Adapter | Description | ++==============+=======================================================+ +| NativeArray | Use a PHP array as source data | ++--------------+-------------------------------------------------------+ +| Model | Use a Phalcon\\Model\\Resultset object as source data | ++--------------+-------------------------------------------------------+ + +Using Paginators +---------------- +In the example below, the paginator will use as its source data the result of a query from a model, and limit the displayed data to 10 records per page: + +.. code-block:: php + + request->getQuery('page', 'int'); // GET + // $this->request->getPost('page', 'int'); // POST + $currentPage = (int) $_GET["page"]; + + // The data set to paginate + $robots = Robots::find(); + + // Create a Model paginator, show 10 rows by page starting from $currentPage + $paginator = new Phalcon\Paginator\Adapter\Model( + array( + "data" => $robots, + "limit"=> 10, + "page" => $numberPage + ) + ); + + // Get the paginated results + $page = $paginator->getPaginate(); + +Variable $currentPage controls the page to be displayed. The $paginator->getPaginate() returns a $page object that contains the paginated data. It can be used for generating the pagination: + +.. code-block:: html+php + + + + + + + + items as $item) { ?> + + + + + + +
IdNameType
id; ?>name; ?>type; ?>
+ +The $page object also contains navigation data: + +.. code-block:: html+php + + First + Previous + Next + Last + + current, " of ", $page->total_pages; ?> + +Page Attributes +--------------- +The $page object has the following attributes: + ++---------+--------------------------------------------------------+ +| Adapter | Description | ++=========+========================================================+ +| items | The set of records to be displayed at the current page | ++---------+--------------------------------------------------------+ +| before | The previous page to the current one | ++---------+--------------------------------------------------------+ +| next | The next page to the current one | ++---------+--------------------------------------------------------+ +| last | The last page in the set of records | ++---------+--------------------------------------------------------+ + diff --git a/zh/reference/phql.rst b/zh/reference/phql.rst new file mode 100644 index 000000000000..88ebc42e12aa --- /dev/null +++ b/zh/reference/phql.rst @@ -0,0 +1,500 @@ +Phalcon Query Language (PHQL) +============================= + +Phalcon Query Language, PhalconQL or simply PHQL is a high level, object oriented SQL dialect that allows to write queries using a +standardized SQL-like language. PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. + +To achieve the highest performance possible, Phalcon provides a parser that uses the same technology as SQLite_. This technology +provides a small in-memory parser with a very low memory footprint that is also thread-safe. + +The parser first checks the syntax of the passed PHQL statement, then builds an intermediate representation of the statement and +finally it converts it to the respective SQL dialect of the target RDBMS. + +Currently, PHQL only supports data manipulation statements such as SELECT, INSERT, UPDATE and DELETE. + +Usage Example +------------- +To better explain how PHQL works consider the following example. We have two models “Cars” and “Brands”: + +.. code-block:: php + + belongsTo('brand_id', 'Brands', 'id'); + } + } + +And every Car has a Brand, so a Brand has many Cars: + +.. code-block:: php + + hasMany('id', 'Cars', 'brand_id'); + } + } + +Creating PHQL Queries +--------------------- +PHQL queries can be created just instantiating the class :doc:`Phalcon\\Mvc\\Model\\Query <../api/Phalcon_Mvc_Model_Query>`: + +.. code-block:: php + + setDI($di); + + // Execute the query returning a result if any + $robots = $query->execute(); + +From a controller or a view, it's easy create/execute them using a injected :doc:`models manager <../api/Phalcon_Mvc_Model_Manager>`: + +.. code-block:: php + + modelsManager->createQuery("SELECT * FROM Cars"); + + $robots = $query->execute(); + +Or simply execute it: + +.. code-block:: php + + modelsManager->executeQuery("SELECT * FROM Cars"); + +Selecting Records +----------------- +As the familiar SQL, PHQL allows querying of records using the SELECT statement we know, except that instead of specifying tables, we use the models classes: + +.. code-block:: php + + createQuery("SELECT * FROM Cars ORDER BY Cars.name"); + $query = $manager->createQuery("SELECT Cars.name FROM Cars ORDER BY Cars.name"); + +Classes in namespaces are also allowed: + +.. code-block:: php + + createQuery($phql); + + $phql = "SELECT Formula\Cars.name FROM Formula\Cars ORDER BY Formula\Cars.name"; + $query = $manager->createQuery($phql); + + $phql = "SELECT c.name FROM Formula\Cars c ORDER BY c.name"; + $query = $manager->createQuery($phql); + +Most of the SQL standard is supported by PHQL even nonstandard directives as LIMIT: + +.. code-block:: php + + createQuery($phql); + +Results Types +^^^^^^^^^^^^^ +Depending on the type of columns we query, the result type will vary. If you retrieve a single whole object then the object returned will be +a :doc:`Phalcon\\Mvc\\Model\\Resultset\\Simple <../api/Phalcon_Mvc_Model_Resultset_Simple>`. This kind of resultset is a set of complete model objects: + +.. code-block:: php + + executeQuery($phql); + foreach ($cars as $car) + { + echo "Name: ", $car->name, "\n"; + } + +This is exactly the same as: + +.. code-block:: php + + "name")); + foreach ($cars as $car) + { + echo "Name: ", $car->name, "\n"; + } + +Complete objects can be modified and re-saved in the database because they represent a complete record of the associated table. There are +other types of queries that do not return complete objects, for example: + +.. code-block:: php + + executeQuery($phql); + foreach ($cars as $car) + { + echo "Name: ", $car->name, "\n"; + } + +We are only requesting some fields in the table therefore those cannot be considered an entire object. In this case also returns a type +resulset :doc:`Phalcon\\Mvc\\Model\\Resultset\\Simple <../api/Phalcon_Mvc_Model_Resultset_Simple>`. However, each element is an standard +object that only contains the two columns that were requested. + +These values ​​that don't represent complete objects we call them scalars. PHQL allows you to query all types of scalars: fields, functions, +literals, expressions, etc..: + +.. code-block:: php + + executeQuery($phql); + foreach ($cars as $car) + { + echo $car->id_name, "\n"; + } + +As we can query complete objects or scalars, also we can query both at once: + +.. code-block:: php + + executeQuery($phql); + +The result in this case is an object :doc:`Phalcon\\Mvc\\Model\\Resultset\\Complex <../api/Phalcon_Mvc_Model_Resultset_Complex>`. +This allows access to both complete objects and scalars at once: + +.. code-block:: php + + cars->name, "\n"; + echo "Price: ", $row->cars->price, "\n"; + echo "Taxes: ", $row->taxes, "\n"; + } + +Scalars are mapped as properties of each "row", while complete objects are mapped as properties with the name of its related model. + +Joins +^^^^^ +It's easy to request records from multiple models using PHQL. Most kinds of Joins are supported. As we defined +relationships in the models. PHQL adds these conditions automatically: + +.. code-block:: php + + executeQuery($phql); + foreach ($rows as $row) + { + echo $row->car_name, "\n"; + echo $row->brand_name, "\n"; + } + +By default, a INNER JOIN is assumed. You can specify the type of JOIN in the query: + +.. code-block:: php + + executeQuery($phql); + + $phql = "SELECT CCars.*, Brands.* FROM Cars LEFT JOIN Brands"; + $rows = $manager->executeQuery($phql); + + $phql = "SELECT Cars.*, Brands.* FROM Cars LEFT OUTER JOIN Brands"; + $rows = $manager->executeQuery($phql); + + $phql = "SELECT Cars.*, Brands.* FROM Cars CROSS JOIN Brands"; + $rows = $manager->executeQuery($phql); + +Also is possibly, manually set the conditions of the JOIN: + +.. code-block:: php + + executeQuery($phql); + +Also, the joins can be created using multiple tables in the FROM clause: + +.. code-block:: php + + executeQuery($phql); + foreach ($rows as $row) + { + echo "Car: ", $row->cars->name, "\n"; + echo "Brand: ", $row->brands->name, "\n"; + } + +Aggregations +^^^^^^^^^^^^ +The following examples show how to use aggregations in PHQL: + +.. code-block:: php + + executeQuery($phql)->getFirst(); + echo $row['summatory']; + + // How many cars are by each brand? + $phql = "SELECT Cars.brand_id, COUNT(*) FROM Cars GROUP BY Cars.brand_id"; + $rows = $manager->executeQuery($phql); + foreach ($rows as $row) + { + echo $row->brand_id, ' ', $row["1"], "\n"; + } + + // How many cars are by each brand? + $phql = "SELECT Brands.name, COUNT(*) FROM Cars JOIN Brands GROUP BY 1"; + $rows = $manager->executeQuery($phql); + foreach ($rows as $row) + { + echo $row->name, ' ', $row["1"], "\n"; + } + + $phql = "SELECT MAX(price) AS maximum, MIN(price) AS minimum FROM Cars"; + $rows = $manager->executeQuery($phql); + foreach ($rows as $row) + { + echo $row["maximum"], ' ', $row["minimum"], "\n"; + } + +Conditions +^^^^^^^^^^ +Conditions allow us to filter the set of records we want to query. The WHERE clause allows to to that: + +.. code-block:: php + + executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE Cars.price > 10000"; + $cars = $manager->executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE TRIM(Cars.name) = 'Audi R8'"; + $cars = $manager->executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE Cars.name LIKE 'Ferrari%'"; + $cars = $manager->executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE Cars.name NOT LIKE 'Ferrari%'"; + $cars = $manager->executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE Cars.price IS NULL"; + $cars = $manager->executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE Cars.id IN (120, 121, 122)"; + $cars = $manager->executeQuery($phql); + + $phql = "SELECT * FROM Cars WHERE Cars.id NOT IN (430, 431)"; + $cars = $manager->executeQuery($phql); + +Also, as part of PHQL, prepared parameters automatically escape the input data, introducing more security: + +.. code-block:: php + + executeQuery($phql, array("name" => 'Lamborghini Espada')); + + $phql = "SELECT * FROM Cars WHERE Cars.name = ?0"; + $cars = $manager->executeQuery($phql, array(0 => 'Lamborghini Espada')); + +Creating Rows +------------- +With PHQL is possible insert data using the familiar INSERT statement: + +.. code-block:: php + + executeQuery($phql); + + // Specifyng columns to insert + $phql = "INSERT INTO Cars (name, brand_id, year, style) " + . "VALUES ('Lamborghini Espada', 7, 1969, 'Grand Tourer')"; + $manager->executeQuery($phql); + + // Inserting using placeholders + $phql = "INSERT INTO Cars (name, brand_id, year, style) " + . "VALUES (:name:, :brand_id:, :year:, :style)"; + $manager->executeQuery($sql, + array( + 'name' => 'Lamborghini Espada', + 'brand_id' => 7, + 'year' => 1969, + 'style' => 'Grand Tourer', + ) + ); + +Phalcon not just only transform the PHQL statements into SQL. All events and business rules defined +in the model are executed as if we created individual objects manually. Let's add a business rule +o the model cars. A car cannot cost less than $ 10,000: + +.. code-block:: php + + price < 10000) + { + $this->appendMessage(new Message("A car cannot cost less than $ 10,000")); + return false; + } + } + + } + +If we made the following INSERT in the the models Cars, the operation will not be successful +because the price does not meet the business rule that we implemented: + +.. code-block:: php + + executeQuery($phql); + if ($result->success() == false) + { + foreach ($result->getMessages() as $message) + { + echo $message->getMessage(); + } + } + +Updating Rows +------------- +Updating rows is very similar than Inserting rows. As you may know, the instruction to +update records is UPDATE. When a record is updated the events related to the update operation +will be executed for each row. + +.. code-block:: php + + executeQuery($phql); + + // Updating multiples columns + $phql = "UPDATE Cars SET price = 15000.00, type = 'Sedan' WHERE id = 101"; + $manager->executeQuery($phql); + + // Updating multiples rows + $phql = "UPDATE Cars SET price = 7000.00, type = 'Sedan' WHERE brands_id > 5"; + $manager->executeQuery($phql); + + // Using placeholders + $phql = "UPDATE Cars SET price = ?0, type = ?1 WHERE brands_id > ?2"; + $manager->executeQuery( + $phql, + array( + 0 => 7000.00, + 1 => 'Sedan', + 2 => 5 + ) + ); + +Deleting Rows +------------- +When a record is deleted the events related to the delete operation will be executed for each row. + +.. code-block:: php + + executeQuery($phql); + + // Deleting multiple rows + $phql = "DELETE FROM Cars WHERE id > 100"; + $manager->executeQuery($phql); + + +.. _SQLite: http://en.wikipedia.org/wiki/Lemon_Parser_Generator \ No newline at end of file diff --git a/zh/reference/request.rst b/zh/reference/request.rst new file mode 100755 index 000000000000..7fa668a9cdbf --- /dev/null +++ b/zh/reference/request.rst @@ -0,0 +1,159 @@ +Request Environment +=================== +Every HTTP request (usually originated by a browser) contains additional information regarding the request such as header data, +files, variables etc. A web based application needs to parse that information so as to provide the correct +response back to the requester. :doc:`Phalcon\\HTTP\\Request <../api/Phalcon_Http_Request>` encapsulates the +information of the request, allowing you to access it in an object oriented way. + +.. code-block:: php + + isPost() == true) { + // Check whether the request was made with Ajax + if ($request->isAjax() == true) { + echo "Request was made using POST and AJAX"; + } + } + +Getting Values +----------------- +PHP automatically fills the superglobal arrays $_GET and $_POST depending on the type of the request. These arrays +contain the values present in forms submitted or the parameters sent via the URL. The variables in the arrays are +never sanitized and can contain illegal characters or even malicious code, which can lead to `SQL injection`_ or +`Cross Site Scripting (XSS)`_ attacks. + +:doc:`Phalcon\\HTTP\\Request <../api/Phalcon_Http_Request>` allows you to access the values stored in the $_GET +and $_POST arrays and sanitize or filter them with :doc:`Phalcon\\Filter <../api/Phalcon_Filter>`. The following +examples offer the same behavior: + +.. code-block:: php + + sanitize($_POST["user_email"], "email"); + + // Manually applying the filter to the value + $filter = new Phalcon\Filter(); + $email = $filter->sanitize($request->getPost("user_email"), "email"); + + // Automatically applying the filter + $email = $request->getPost("user_email", "email"); + + +Accessing the Request from Controllers +-------------------------------------- +The most common place to access the request environment is in an action of a controller. To access the +:doc:`Phalcon\\HTTP\\Request <../api/Phalcon_Http_Request>` object from a controller you will need to use +the $this->request public property of the controller: + +.. code-block:: php + + request->isPost() == true) { + + // Access POST data + $customerName = $this->request->getPost("name"); + $customerBorn = $this->request->getPost("born"); + + } + + } + + } + +Uploading Files +--------------- +Another common task is file uploading. :doc:`Phalcon\\HTTP\\Request <../api/Phalcon_Http_Request>` offers +an object-oriented way to achieve this task: + +.. code-block:: php + + request->hasFiles() == true) { + // Print the real file names and sizes + foreach ($this->request->getUploadedFiles() as $file) { + echo $file->getName(), " ", $file->getSize(), "\n"; + } + } + } + + } + +Each object returned by Phalcon\\Http\\Request::getUploadedFiles() is an instance of the +:doc:`Phalcon\\Http\\Request\\File <../api/Phalcon_Http_Request_File>` class. Using the $_FILES superglobal +array offers the same behavior. :doc:`Phalcon\\Http\\Request\\File <../api/Phalcon_Http_Request_File>` encapsulates +only the information related to each file uploaded with the request. + +Working with Headers +-------------------- +As mentioned above, request headers contain useful information that allow us to send the proper response back to t +he user. The following examples show usages of that information: + +.. code-block:: php + + getHeader("X_REQUESTED_WITH"); + if ($requestedWith == "XMLHttpRequest") { + echo "The request was made with Ajax"; + } + + // Same as above + if ($request->isAjax()) { + echo "The request was made with Ajax"; + } + + // Check the request layer + if ($request->isSecureRequest() == true) { + echo "The request was made using a secure layer"; + } + + // Get the servers's ip address. ie. 192.168.0.100 + $ipAddress = $request->getServerAddress(); + + // Get the client's ip address ie. 201.245.53.51 + $ipAddress = $request->getClientAddress(); + + // Get the User Agent (HTTP_USER_AGENT) + $userAgent = $request->getUserAgent(); + + // Get the best acceptable content by the browser. ie text/xml + $contentType = $request->getAcceptableContent(); + + // Get the best charset accepted by the browser. ie. utf-8 + $charset = $request->getBestCharset(); + + // Get the best language accepted configured in the browser. ie. en-us + $language = $request->getBestLanguage(); + + +.. _SQL injection: http://en.wikipedia.org/wiki/SQL_injection +.. _Cross Site Scripting (XSS): http://en.wikipedia.org/wiki/Cross-site_scripting diff --git a/zh/reference/response.rst b/zh/reference/response.rst new file mode 100644 index 000000000000..0891d7445667 --- /dev/null +++ b/zh/reference/response.rst @@ -0,0 +1,70 @@ +Returning Responses +=================== + +Part of the HTTP cycle is return responses to the clients. :doc:`Phalcon\\HTTP\\Response <../api/Phalcon_Http_Response>` is the Phalcon +component designed to achieve this task. HTTP responses are usually composed by headers and body. The basic usage is the following: + +.. code-block:: php + + setRawHeader(404, "Not Found"); + + //Set the content of the response + $response->setContent("Sorry, the page doesn't exists"); + + //Send response to the client + $response->send(); + +Working with Headers +-------------------- +Headers are an important part of the whole HTTP response. It contains useful information about the response state like the HTTP status, +type of response and much more. + +You can set headers in the following way: + +.. code-block:: php + + setHeader("Content-Type", "application/pdf"); + $response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"'); + + //Setting a raw header + $response->setRawHeader("HTTP/1.1 200 OK"); + +A :doc:`Phalcon\\HTTP\\Response\\Headers <../api/Phalcon_Http_Response_Headers>` bag internally manages headers. This class +allows to manage headers before sent it to client: + +.. code-block:: php + + getHeaders(); + + //Get a header by its name + $contentType = $response->getHeaders()->get("Content-Type"); + +Making Redirections +------------------- +With :doc:`Phalcon\\HTTP\\Response <../api/Phalcon_Http_Response>` you can also make HTTP redirections: + +.. code-block:: php + + redirect("posts/index"); + + //Making a redirection to an external URL + $response->redirect("http://en.wikipedia.org", true); + + //Making a redirection specifyng the HTTP status code + $response->redirect("http://www.example.com/new-location", true, 301); + diff --git a/zh/reference/routing.rst b/zh/reference/routing.rst new file mode 100755 index 000000000000..558551fc4611 --- /dev/null +++ b/zh/reference/routing.rst @@ -0,0 +1,477 @@ +Routing +======= +The router component allows defining routes that are mapped to controllers or handlers that should receive +the request. A router simply parses a URI to determine this information. The router has two modes: MVC +mode and match-only mode. The first mode is ideal for working with MVC applications. + +Defining Routes +--------------- +:doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` provides advanced routing capabilities. In MVC mode, +you can define routes and map them to controllers/actions that you require. A route is defined as follows: + +.. code-block:: php + + add( + "/admin/users/my-profile", + array( + "controller" => "users", + "action" => "profile", + ) + ); + + //Another route + $router->add( + "/admin/users/change-password", + array( + "controller" => "users", + "action" => "changePassword", + ) + ); + + $router->handle(); + +The method add() receives as first parameter a pattern and optionally a set of paths as second parameter. +In this case if the URI is exactly: /admin/users/my-profile, then the "users" controller with its action "profile" +will be executed. Currently, the router does not execute the controller and action, it only collects this +information to inform the correct component (ie. :doc:`Phalcon\\Mvc\\Dispatcher <../api/Phalcon_Mvc_Dispatcher>`) +that this is controller/action it should to execute. + +An application can have many paths, define routes one by one can be a cumbersome task. In these cases we can +create more flexible routes: + +.. code-block:: php + + add( + "/admin/:controller/a/:action/:params", + array( + "controller" => 1, + "action" => 2, + "params" => 3, + ) + ); + +In the example above, using wildcards we make a route valid for many URIs. For example, by accessing the +following URL (/admin/users/a/delete/dave/301) then: + ++------------+---------------+ +| Controller | users | ++------------+---------------+ +| Action | delete | ++------------+---------------+ +| Parameter | dave | ++------------+---------------+ +| Parameter | 301 | ++------------+---------------+ + +The method add() receives a pattern that optionally could have predefined placeholders and regular expression +modifiers. All the routing patterns must start with a slash character (/). The regular expression syntax used +is the same as the `PCRE regular expressions`_. Note that, it is not necessary to add regular expression +delimiters. All routes patterns are case-insensitive. + +The second parameter defines how the matched parts should bind to the controller/action/parameters. Matching +parts are placeholders or subpatterns delimited by parentheses (round brackets). In the above example, the +first subpattern matched (:controller) is the controller part of the route, the second the action and so on. + +These placeholders help writing regular expressions that are more readable for developers and easier +to understand. The following placeholders are supported: + ++--------------+--------------------+--------------------------------------------------------------------+ +| Placeholder | Regular Expression | Usage | ++==============+====================+====================================================================+ +| /:module | /([a-zA-Z0-9\_]+) | Matches a valid module name with alpha-numeric characters only | ++--------------+--------------------+--------------------------------------------------------------------+ +| /:controller | /([a-zA-Z0-9\_]+) | Matches a valid controller name with alpha-numeric characters only | ++--------------+--------------------+--------------------------------------------------------------------+ +| /:action | /([a-zA-Z0-9\_]+) | Matches a valid action name with alpha-numeric characters only | ++--------------+--------------------+--------------------------------------------------------------------+ +| /:params | (/.*)* | Matches a list of optional words separated by slashes | ++--------------+--------------------+--------------------------------------------------------------------+ + +Since you can add many routes as you need using add(), the order in which you add the routes indicates +their relevance, last routes added have more relevance than first added. Internally, all defined routes +are traversed in reverse order until :doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` finds the +one that matches the given URI and processes it, while ignoring the rest. + +Parameters with Names +^^^^^^^^^^^^^^^^^^^^^ +The example below demonstrates how to define names to route parameters: + +.. code-block:: php + + add( + "/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params", + array( + "controller" => "posts", + "action" => "show", + "year" => 1, // ([0-9]{4}) + "month" => 2, // ([0-9]{2}) + "day" => 3, // ([0-9]{2}) + "params" => 4, // :params + ) + ); + +In the above example, the route doesn't define a "controller" or "action" part. These parts are replaced +with fixed values ("posts" and "show"). The user will not know the controller that is really dispatched +by the request. Inside the controller, those named parameters can be accessed as follows: + +.. code-block:: php + + dispatcher->getParam("year"); + + // Return "month" parameter + $month = $this->dispatcher->getParam("month"); + + // Return "day" parameter + $day = $this->dispatcher->getParam("day"); + + } + + } + +Note that the values ​​of the parameters are obtained from the dispatcher. This happens because it is the +component that finally interacts with the drivers of your application. Moreover, there is also another +way to create named parameters as part of the pattern: + +.. code-block:: php + + add( + "/documentation/{chapter}/{name}.{type:[a-z]+}", + array( + "controller" => "documentation", + "action" => "show" + ) + ); + +You can access their values ​​in the same way as before: + +.. code-block:: php + + dispatcher->getParam("name"); + + // Returns "type" parameter + $year = $this->dispatcher->getParam("type"); + + } + + } + +Short Syntax +^^^^^^^^^^^^ +If you don't like using an array to define the route paths, an alternative syntax is also available. +The following examples produce the same result: + +.. code-block:: php + + add("/posts/{year:[0-9]+}/{title:[a-z\-]+}", "Posts::show"); + + // Array form: + $router->add( + "/posts/([0-9]+)/([a-z\-]+)", + array( + "controller" => "posts", + "action" => "show", + "year" => 1, + "title" => 2, + ) + ); + + +Routing to Modules +^^^^^^^^^^^^^^^^^^ +You can define routes whose paths include modules. This is specially suitable to multi-module applications. +It's possible define a default route that includes a module wildcard: + +.. code-block:: php + + add('/:module/:controller/:action/:params', array( + 'module' => 1, + 'controller' => 2, + 'action' => 3, + 'params' => 4 + )); + +In this case, the route always must have the module name as part of the URL. For example, the following +URL: /admin/users/edit/sonny, will be processed as: + ++------------+---------------+ +| Module | admin | ++------------+---------------+ +| Controller | users | ++------------+---------------+ +| Action | edit | ++------------+---------------+ +| Parameter | sonny | ++------------+---------------+ + +Or you can bind specific routes to specific modules: + +.. code-block:: php + + add("/login", array( + 'module' => 'backend', + 'controller' => 'login', + 'action' => 'index', + )); + + $router->add("/products/:action", array( + 'module' => 'frontend', + 'controller' => 'products', + 'action' => 1, + )); + +HTTP Method Restrictions +^^^^^^^^^^^^^^^^^^^^^^^^ +When you add a route using simply add(), the route will be enabled for any HTTP method. Sometimes we can restrict a route to a specific method, +this is especially useful when creating RESTful applications: + +.. code-block:: php + + addGet("/products/edit/{id}", "Posts::edit"); + + // This route only will be matched if the HTTP method is POST + $router->addPost("/products/save", "Posts::save"); + + // This route will be matched if the HTTP method is POST or PUT + $router->add("/products/update")->via(array("POST", "PUT")); + +Matching Routes +--------------- +Now we must a URI to Router in order that it check which is the defined route that matches the given URI. +By default, the routing URI is taken from the $_GET['_url'] variable that is created by the rewrite engine +module. A couple of rewrite rules that work very well with Phalcon are: + +.. code-block:: apacheconf + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + +The following example shows how to use this component: + +.. code-block:: php + + handle(); + + // or Setting the URI value directly + $router->handle("/employees/edit/17"); + + // Getting the processed controller + echo $router->getControllerName(); + + // Getting the processed action + echo $router->getActionName(); + + //Get the matched route + $route = $router->getMatchedRoute(); + +Naming Routes +------------- +Each route that is added to the router is stored internally as an object :doc:`Phalcon\\Mvc\\Router\\Route <../api/Phalcon_Mvc_Router_Route>`. +That class encapsulates all the details of each route. For instance, we can give a name to a path to identify it uniquely in our application. +This is especially useful if you want to create URLs from it. + +.. code-block:: php + + add("/posts/{year}/{title}", "Posts::show"); + + $route->setName("show-posts"); + + //or just + + $router->add("/posts/{year}/{title}", "Posts::show")->setName("show-posts"); + +Then, using for example the component :doc:`Phalcon\\Mvc\\Url <../api/Phalcon_Mvc_Url>` we can build routes from its name: + +.. code-block:: php + + get(array("for" => "show-posts", "year" => "2012", "title" => "phalcon-1-0-released")); + +Usage Examples +-------------- +The following are examples of custom routes: + +.. code-block:: php + + add( + "/system/:controller/a/:action/:params", + array( + "controller" => 1, + "action" => 2, + "params" => 3, + ) + ); + + // matches "/es/news" + $router->add( + "/([a-z]{2})/:controller", + array( + "controller" => 2, + "action" => "index", + "language" => 1, + ) + ); + + // matches "/es/news" + $router->add( + "/{language:[a-z]{2}}/:controller", + array( + "controller" => 2, + "action" => "index", + ) + ); + + // matches "/admin/posts/edit/100" + $router->add( + "/admin/:controller/:action/:int", + array( + "controller" => 1, + "action" => 2, + "id" => 3, + ) + ); + + // matches "/posts/2010/02/some-cool-content" + $router->add( + "/posts/([0-9]{4})/([0-9]{2})/([a-z\-]+)", + array( + "controller" => "posts", + "action" => "show", + "year" => 1, + "month" => 2, + "title" => 4, + ) + ); + + // matches "/manual/en/translate.adapter.html" + $router->add( + "/manual/([a-z]{2})/([a-z\.]+)\.html", + array( + "controller" => "manual", + "action" => "show", + "language" => 1, + "file" => 2, + ) + ); + + // matches /feed/fr/le-robots-hot-news.atom + $router->add( + "/feed/{lang:[a-z]+}/{blog:[a-z\-]+}\.{type:[a-z\-]+}", + "Feed::get" + ); + +Default Behavior +---------------- +:doc:`Phalcon\\Mvc\\Router <../api/Phalcon_Mvc_Router>` has a default behavior providing a very simple routing that +always expects a URI that matches the following pattern: /:controller/:action/:params + +For example, for a URL like this *http://phalconphp.com/documentation/show/about.html*, this router will translate it as follows: + ++------------+---------------+ +| Controller | documentation | ++------------+---------------+ +| Action | show | ++------------+---------------+ +| Parameter | about.html | ++------------+---------------+ + +If you don't want use this routes as default in your application, you must create the router passing false as parameter: + +.. code-block:: php + + setDefaultController("index"); + $router->setDefaultAction("index"); + + //Using an array + $router->setDefaults(array( + "controller" => "index", + "action" => "index" + )); + +.. _PCRE regular expressions: http://www.php.net/manual/en/book.pcre.php + + + diff --git a/zh/reference/session.rst b/zh/reference/session.rst new file mode 100644 index 000000000000..a2c7ecd7ec06 --- /dev/null +++ b/zh/reference/session.rst @@ -0,0 +1,171 @@ +Storing data in Session +======================= + +The :doc:`Phalcon\\Session <../api/Phalcon_Session>` provides object-oriented wrappers to access session data. + +Starting the Session +-------------------- +Some applications are session-intensive, almost any action that performs requires access to session data. There are others who access session data casually. +Thanks to the service container, we can ensure that the session is accessed only when it's clearly needed: + +.. code-block:: php + + set('session', function(){ + $session = new Phalcon\Session\Adapter\Files(); + $session->start(); + return $session; + }); + +Storing/Retrieving data in Session +---------------------------------- +From a controller, a view or any other component thats extends :doc:`Phalcon\\DI\\Injectable <../api/Phalcon_DI_Injectable>` you can access the session service +and store items and retrieve them in the following way: + +.. code-block:: php + + session->set("user-name", "Michael"); + } + + public function welcomeAction() + { + + //Check if the variable is defined + if ($this->session->has("user-name")) + { + + //Retrieve its value + $name = $this->session->get("user-name"); + } + } + + } + +Removing/Destroying Sessions +---------------------------- +It's also possible remove specific variables or destroy the whole session: + +.. code-block:: php + + session->remove("user-name"); + } + + public function logoutAction() + { + //Destroy the whole session + $this->session->destroy(); + } + + } + +Isolating Session Data between Applications +------------------------------------------- +Sometimes a user can use the same application twice, on the same server, in the same session. Surely, if we use variables in session, +we want that every application have separate session data (even though the same code and same variable names). To solve this, you can add a +prefix for every session variable created in a certain application: + +.. code-block:: php + + set('session', function(){ + + //All variables created will prefixed with "my-app-1" + $session = new Phalcon\Session\Adapter\Files( + array( + 'uniqueId' => 'my-app-1' + ) + ); + + $session->start(); + + return $session; + }); + +Session Bags +------------ +:doc:`Phalcon\\Session\\Bag <../api/Phalcon_Session_Bag>` is a component helps that helps separing session data into "namespaces". +Working by this way you can easily create groups of session variables into the application. By only setting the variables in the "bag", +it's automatically stored in session: + +.. code-block:: php + + name = "Kimbra Johnson"; + $user->age = 22; + + +Persistent Data in Components +----------------------------- +Controller, components and classes thats extends :doc:`Phalcon\\DI\\Injectable <../api/Phalcon_DI_Injectable>` may inject +a :doc:`Phalcon\\Session\\Bag <../api/Phalcon_Session_Bag>`. This class isolates variables for every class. +Thanks to this you can persist data between requests in every class in an independent way. + +.. code-block:: php + + persistent->name = "Laura"; + } + + public function welcomeAction() + { + if (isset($this->persistent->name)) + { + echo "Welcome, ", $this->persistent->name; + } + } + + } + +In a component: + +.. code-block:: php + + persistent->name = "Laura"; + } + + public function getAuthName() + { + return $this->persistent->name; + } + + } + +The data added to the session ($this->session) are available throughout the application, while persistent ($this->persistent) +can only be accessed in the scope of the current class. diff --git a/zh/reference/tags.rst b/zh/reference/tags.rst new file mode 100755 index 000000000000..ec33c5f54479 --- /dev/null +++ b/zh/reference/tags.rst @@ -0,0 +1,432 @@ +View Helpers +============ +Writing and maintaining HTML markup can quickly become a tedious task because of the naming conventions and numerous attributes that have to be taken into consideration. Phalcon deals with this complexity by offering :doc:`Phalcon\\Tag <../api/Phalcon_Tag>`, which in turn offers view helpers to generate HTML markup. + +.. highlights:: + This guide is not intended to be a complete documentation of available helpers and their arguments. Please visit the :doc:`Phalcon\\Tag <../api/Phalcon_Tag>` page in the API for a complete reference. + +Using Name Aliasing +------------------- +You could use name aliasing to get short names for classes. In this case, a Tag name can be used to alias the :doc:`Phalcon\\Tag <../api/Phalcon_Tag>` class. + +.. code-block:: php + + + +Document Type of Content +------------------------ +Phalcon provides Phalcon\\Tag::setDoctype() helper to set document type of the content. Document type setting may affect HTML output produced by other tag helpers. +For example, if you set XHTML document type family, helpers that return or output HTML tags will produce self-closing tags to follow valid XHTML standard. + +Available document type constants in Phalcon\\Tag namespace are: + ++----------------------+------------------------+ +| Constant | Document type | ++======================+========================+ +| HTML32 | HTML 3.2 | ++----------------------+------------------------+ +| HTML401_STRICT | HTML 4.01 Strict | ++----------------------+------------------------+ +| HTML401_TRANSITIONAL | HTML 4.01 Transitional | ++----------------------+------------------------+ +| HTML401_FRAMESET | HTML 4.01 Frameset | ++----------------------+------------------------+ +| HTML5 | HTML 5 | ++----------------------+------------------------+ +| XHTML10_STRICT | XHTML 1.0 Strict | ++----------------------+------------------------+ +| XHTML10_TRANSITIONAL | XHTML 1.0 Transitional | ++----------------------+------------------------+ +| XHTML10_FRAMESET | XHTML 1.0 Frameset | ++----------------------+------------------------+ +| XHTML11 | XHTML 1.1 | ++----------------------+------------------------+ +| XHTML20 | XHTML 2.0 | ++----------------------+------------------------+ +| XHTML5 | XHTML 5 | ++----------------------+------------------------+ + +Setting document type. + +.. code-block:: php + + + +Getting document type. + +.. code-block:: html+php + + + + + + +The following HTML will be produced. + +.. code-block:: html + + + + + + +Generating Links +---------------- +A real common task in any web application or website is to produce links that allow us to navigate from one page to another. +When they are internal URLs we can create them in the following manner: + +.. code-block:: html+php + + + + + + 'show-product', 'id' => 123, 'name' => 'carrots')) ?> + +Actually, all produced URLs are generated by the component :doc:`Phalcon\\Mvc\\Url ` (or service "url" failing) + +Creating Forms +-------------- +Forms in web applications play an essential part in retrieving user input. The following example shows how to implement a simple search form using view helpers: + +.. code-block:: html+php + + + + + + + + + + + + "get")); ?> + + + + + +This last code will generate the following HTML: + +.. code-block:: html+php + +
+ + + + + +Helpers to Generate Form Elements +--------------------------------- +Phalcon provides a series of helpers to generate form elements such as text fields, buttons and more. The first parameter of each helper is always the name of the element to be generated. When the form is submitted, the name will be passed along with the form data. In a controller you can get these values using the same name by using the getPost() and getQuery() methods on the request object ($this->request). + +.. code-block:: html+php + + "5" + )) ?> + + "6", + "rows" => 20 + )) ?> + + + + "5" + )) ?> + +Making Select Boxes +------------------- +Generating select boxes (select box) is easy, especially if the related data is stored in PHP associative arrays. The helpers for select elements are Phalcon\\Tag::select() and Phalcon\\Tag::selectStatic(). +Phalcon\\Tag::selectStatic() has been was specifically designed to work with :doc:`Phalcon\\Mvc\\Model `, while Phalcon\\Tag::selectStatic() can with PHP arrays. + +.. code-block:: php + + array("id", "name") + ) + ); + + // Using data from an array + echo Phalcon\Tag::selectStatic( + array( + "status", + array( + "A" => "Active", + "I" => "Inactive", + ) + ) + ); + +The following HTML will generated: + +.. code-block:: html + + + + + +Assigning HTML attributes +------------------------- +All the helpers accept an array as their first parameter which can contain additional HTML attributes for the element generated. + +.. code-block:: html+php + + 20, + "maxlength" => 30, + "placeholder" => "Enter a price", + ) + ) ?> + +The following HTML will generated: + +.. code-block:: html + + + +Setting Helper Values +--------------------- + +From Controllers +^^^^^^^^^^^^^^^^ +It is a good programming principle for MVC frameworks to set specific values for form elements in the view. +You can set those values directly from the controller using Phalcon\\Tag::setDefaultValue(). +This helper preloads a value for any helpers present in the view. If any helper in the view has +a name that matches the preloaded value, it will use it, unless a value is directly assigned on the helper in the view. + +.. code-block:: php + + "Yellow", + "Blue" => "Blue", + "Red" => "Red" + ) + ) + ); + +This will generate the following select tag with the value "Blue" selected: + +.. code-block:: html + + + +From the Request +^^^^^^^^^^^^^^^^ +A special feature that the :doc:`Phalcon\\Tag <../api/Phalcon_Tag>` helpers have is that they keep the values +of form helpers between requests. This way you can easily show validation messages without losing entered data. + +Specifying values directly +^^^^^^^^^^^^^^^^^^^^^^^^^^ +Every form helper supports the parameter "value". With it you can specify a value for the helper directly. +When this parameter is present, any preset value using setDefaultValue() or via request will be ignored. + +Changing dynamically the Document Title +--------------------------------------- +:doc:`Phalcon\\Tag <../api/Phalcon_Tag>` offers helpers to change dynamically the document title from the controller. +The following example demonstrates just that: + +.. code-block:: php + + + + <?php \Phalcon\Tag::getTitle(); ?> + + + + + + +The following HTML will generated: + +.. code-block:: html+php + + + + Index of Posts - Your Website + + + + + + +Static Content Helpers +---------------------- +:doc:`Phalcon\\Tag <../api/Phalcon_Tag>` also provide helpers to generate tags such as script, link or img. They aid in quick and easy generation of the static resources of your application + +Images +^^^^^^ + +.. code-block:: php + + + echo \Phalcon\Tag::image("img/hello.gif"); + + // Generate alternative text + echo \PhalconTag::image( + array( + "img/hello.gif", + "alt" => "alternative text" + ) + ); + +Stylesheets +^^^^^^^^^^^ + +.. code-block:: php + + + echo \Phalcon\Tag::stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false); + + // Generate + echo \Phalcon\Tag::stylesheetLink("css/styles.css"); + +Javascript +^^^^^^^^^^ + +.. code-block:: php + + + echo \Phalcon\Tag::javascriptInclude("http://localhost/javascript/jquery.min.js", false); + + // Generate + echo \Phalcon\Tag::javascriptInclude("javascript/jquery.min.js"); + +Creating your own helpers +------------------------- +You can easily create your own helpers by extending the :doc:`Phalcon\\Tag <../api/Phalcon_Tag>` and implementing your own helper. Below is a simple example of a custom helper: + +.. code-block:: php + + $attributeValue) { + if (!is_integer($key)) { + $code.= $key.'="'.$attributeValue.'" '; + } + } + $code.=" />"; + + return $code; + } + + } + +In next chapter, we'll talk about :doc:`Volt ` a faster template engine for PHP, where you can use a +more friendly syntax for using helpers provided by Phalcon\Tag. \ No newline at end of file diff --git a/zh/reference/tools.rst b/zh/reference/tools.rst new file mode 100755 index 000000000000..809e09adc588 --- /dev/null +++ b/zh/reference/tools.rst @@ -0,0 +1,301 @@ +Phalcon Developer Tools +======================= +These tools are a collection of useful scripts to generate skeleton code. Core components of your application can be generated with +a simple command, allowing you to easily develop applications using Phalcon. + +.. highlights:: + **Important:** Phalcon Framework version 0.5.0 or greater is needed to use developer tools. It is highly recommended + to use PHP 5.3.6 or greater. If you prefer to use the web version instead of the console, this `blog post`_ offers more information. + +Download +-------- +You can download or clone a cross platform package containing the developer tools from Github_. + +Installation +^^^^^^^^^^^^ +These are detailed instructions on how to install the developer tools on different platforms: + +.. toctree:: + :maxdepth: 1 + + wintools + mactools + linuxtools + +Getting Available Commands +-------------------------- +You can get a list of available commands in Phalcon tools by typing: phalcon commands + +.. figure:: ../_static/img/tools-4.png + :align: center + +Generating a Project Skeleton +----------------------------- +You can use Phalcon tools to generate pre-defined project skeletons for your applications with Phalcon framework. By default the +project skeleton generator will use mod_rewrite for Apache. Type the following command on your web server document root: + +.. figure:: ../_static/img/tools-1.png + :align: center + +The above recommended project structure was generated: + +.. figure:: ../_static/img/tools-2.png + :align: center + +You could add the parameter *--help* to get help on the usage of a certain script: + +.. figure:: ../_static/img/tools-3.png + :align: center + +Accessing the project from the web server will show you: + +.. figure:: ../_static/img/tools-6.png + :align: center + +Generating Controllers +---------------------- +The command "create-controller" generates controller skeleton structures. It's important to invoke this command inside a directory +that already has a Phalcon project. + +.. figure:: ../_static/img/tools-5.png + :align: center + +The following code is generated by the script: + +.. code-block:: php + + id = $id; + } + + /** + * Method to set the value of field types_id + * @param integer $types_id + */ + public function setTypesId($types_id) + { + $this->types_id = $types_id; + } + + ... + + /** + * Returns the value of field status + * @return string + */ + public function getStatus() + { + return $this->status; + } + + } + +A nice feature of the model generator is that it keeps changes made by the developer between code generations. This allows the +addition or removal of fields and properties, without worrying about losing changes made to the model itself. +The following screencast shows you how it works: + +.. raw:: html + +
+ +Scaffold a CRUD +--------------- +Scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and +controllers for a new resource in a single operation, scaffolding is the tool for the job. + +Once the code is generated, it will have to be customized to meet your needs. Many developers avoid scaffolding entirely, opting +to write all or most of their source code from scratch. The generated code can serve as a guide to better understand of how the +framework works or develop prototypes. The screenshot below shows a scaffold based on the table "products": + +.. figure:: ../_static/img/tools-9.png + :align: center + +The scaffold generator will build several files in your application, along with some folders. Here's a quick overview of what will be generated: + ++----------------------------------------+--------------------------------+ +| File | Purpose | ++========================================+================================+ +| app/controllers/ProductsController.php | The Products controller | ++----------------------------------------+--------------------------------+ +| app/models/Products.php | The Products model | ++----------------------------------------+--------------------------------+ +| app/views/layout/products.phtml | Controller layout for Products | ++----------------------------------------+--------------------------------+ +| app/views/products/new.phtml | View for the action "new" | ++----------------------------------------+--------------------------------+ +| app/views/products/edit.phtml | View for the action "edit" | ++----------------------------------------+--------------------------------+ +| app/views/products/search.phtml | View for the action "search" | ++----------------------------------------+--------------------------------+ +| app/views/products/edit.phtml | View for the action "edit" | ++----------------------------------------+--------------------------------+ + +When browsing the recently generated controller, you will see a search form and a link to create a new Product: + +.. figure:: ../_static/img/tools-10.png + :align: center + +The "create page" allows you to create products applying validations on the Products model. Phalcon will automatically validate +not null fields producing warnings if any of them is required. + +.. figure:: ../_static/img/tools-11.png + :align: center + +After performing a search, a pager component is available to show paged results. Use the "Edit" or "Delete" links in front of each result to perform such actions. + +.. figure:: ../_static/img/tools-12.png + :align: center + +Web Interface to Tools +---------------------- +Also, if you prefer, it's possible to use Phalcon Developer Tools from a web interface. Check out the following screencast to figure out how it works: + +.. raw:: html + +
+ +Integrating Tools with PhpStorm IDE +----------------------------------- +The screencast below shows how to integrate developer tools with the `PhpStorm IDE`_. The configuration steps could be easily adapted to other IDEs for PHP. + +.. raw:: html + +
+ +Conclusion +---------- +Phalcon Developer Tools provides an easy way to generate code for your application, reducing development time and potential coding errors. + +.. _blog post: http://blog.phalconphp.com/post/23251010409/dont-like-command-line-and-consoles-no-problem +.. _Github: https://github.com/phalcon/phalcon-devtools +.. _Bootstrap: http://twitter.github.com/bootstrap/ +.. _PhpStorm IDE: http://www.jetbrains.com/phpstorm/ \ No newline at end of file diff --git a/zh/reference/translate.rst b/zh/reference/translate.rst new file mode 100755 index 000000000000..f63fb5948633 --- /dev/null +++ b/zh/reference/translate.rst @@ -0,0 +1,118 @@ +Multi-lingual Support +===================== +The component :doc:`Phalcon\\Translate <../api/Phalcon_Translate>` aids in creating multilingual applications. Applications using this component, +display content in different languages, based on the user's chosen language supported by the application. + +Adapters +-------- +This component makes use of adapters to read translation messages from different sources in a unified way. + ++-------------+-----------------------------------------------------------------------------------------+ +| Adapter | Description | ++=============+=========================================================================================+ +| NativeArray | Uses PHP arrays to store the messages. This is the best option in terms of performance. | ++-------------+-----------------------------------------------------------------------------------------+ + +Component Usage +--------------- +Translation strings are stored in files. The structure of these files could vary depending of the adapter used. Phalcon gives you the freedom +to organize your translation strings. A simple structure could be: + +.. code-block:: bash + + app/messages/en.php + app/messages/es.php + app/messages/fr.php + app/messages/zh.php + +Each file contains an array of the translations in a key/value manner. For each translation file, keys are unique. The same array is used in +different files, where keys remain the same and values contain the translated strings depending on each language. + +.. code-block:: php + + "Hello", + "bye" => "Good Bye", + "hi-name" => "Hello %name%", + "song" => "This song is %song%" + ); + +.. code-block:: php + + "Bonjour", + "bye" => "Au revoir", + "hi-name" => "Bonjour %name%", + "song" => "La chanson est %song%" + ); + +Implementing the translation mechanism in your application is trivial but depends on how you wish to implement it. You can use an +automatic detection of the language from the user's browser or you can provide a settings page where the user can select their language. + +A simple way of detecting the user's language is to parse the $_SERVER['HTTP_ACCEPT_LANGUAGE'] contents, or if you wish, access it +directly by calling $this->request->getBestLanguage() from an action/controller: + +.. code-block:: php + + request->getBestLanguage(); + + //Check if we have a translation file for that lang + if (file_exists("app/messages/".$language.".php")) { + require "app/messages/".$language.".php"; + } else { + // fallback to some default + require "app/messages/en.php"; + } + + //Return a translation object + return new \Phalcon\Translate\Adapter\NativeArray(array( + "content" => $messages + )); + + } + + public function indexAction() + { + $this->view->setVar("name", "Mike"); + $this->view->setVar("t", $this->_getTranslation()); + } + + } + +The _getTranslation method is available for all actions that require translations. The $t variable is passed to the views, and with it, +we can translate strings in that layer: + +.. code-block:: html+php + + + +

_("hi"), " ", $name; ?>

+ +The "_" function is returning the translated string based on the index passed. Some strings need to incorporate placeholders for +calculated data i.e. Hello %name%. These placeholders can be replaced with passed parameters in the "_ function. The passed parameters +are in the form of a key/value array, where the key matches the placeholder name and the value is the actual data to be replaced: + +.. code-block:: html+php + + + +

_("hi-user", array("name" => $name)); ?>

+ +Some applications implement multilingual on the URL such as http://www.mozilla.org/**es-ES**/firefox/. Phalcon can implement +this by using a :doc:`Router `. + diff --git a/zh/reference/tutorial-invo.rst b/zh/reference/tutorial-invo.rst new file mode 100644 index 000000000000..5fc3cd838166 --- /dev/null +++ b/zh/reference/tutorial-invo.rst @@ -0,0 +1,944 @@ +教程 2: 解读分析 INVO 项目 +=========================== + +在第二个教程中,我们将解读分析一个更完整的应用程序,以强化你对Phalcon的理解,INVO是我们已经创建了的作为示例程序的应用程序之一。你可以从 Github_ 获得INVO的全部代码。 + +此外还需要说明的是,INVO的html实现是使用 `Twitter Bootstrap `_ CSS framework来完成的,在这个示例项目中,并不真正的生成发票(这是一个类似于进销存的相关的应用),但它作为一个例子还是可以告诉你整个框架是如何工作的。 + +项目目录结构 +------------------ +从Github上克隆了源代码后,你可以发现目录结构是这样的: + +.. code-block:: bash + + invo/ + app/ + app/config/ + app/controllers/ + app/library/ + app/models/ + app/plugins/ + app/views/ + public/ + public/bootstrap/ + public/css/ + public/js/ + schemas/ + +在前面的章节已经讲过,Phalcon并没有固定的目录结构,该项目提供了一个简单的MVC目录结构。 + +通过浏览器打开应用程序 http://localhost/invo 显示效果如下: + +.. figure:: ../_static/img/invo-1.png + :align: center + +INVO应用程序分为两部分,即通常我们说的前台后台。前台部分,用户可以通过INVO查看一些信息,同时可以提交联系方式。后台部分,相当于管理区域,在这里面注册用户可以管理自己的产品和客户。 + +标准路由器 +--------------- +INVO使用标准的内奸路由器组件,此路由的匹配模式如下 /:controller/:action/:params ,这意味着,URL中的第一部分是控制器,第二个是action方法。 + +路由 /session/register 将要执行SessionController中的RegisterAction方法 + +Configuration +------------- +INVO有一个配置文件,用于设置一些常用的数据,比如数据库连接参数,目录结构等。在引导文件 (public/index.php) 的第一部分,可以这样读取配置文件 + +.. code-block:: php + + ` 使得读取配置内容是面像对象的,配置文件的定义如下: + +.. code-block:: ini + + [database] + host = localhost + username = root + password = secret + name = invo + + [application] + controllersDir = /../app/controllers/ + modelsDir = /../app/models/ + viewsDir = /../app/views/ + pluginsDir = /../app/plugins/ + libraryDir = /../app/library/ + baseUri = /invo/ + + ;[metadata] + ;adapter = "Apc" + ;suffix = my-suffix + ;lifetime = 3600 + +Phalcon的配置文件可以分类进行定义,在这个文件中,共定义了三个部分 database,application,metadata + +Autoloaders +----------- +在引导文件 (public/index.php) 的第二部分是autoloader,autoloader注册了一些目录,在这些目录中放置的是我们应用程序需要用到的类文件 + +.. code-block:: php + + registerDirs( + array( + __DIR__.$config->application->controllersDir, + __DIR__.$config->application->pluginsDir, + __DIR__.$config->application->libraryDir, + __DIR__.$config->application->modelsDir, + ) + )->register(); + +需要注意的是,注册的这些目录并不包括 viewsDir,因为viewsDir中并不包含classes文件,而是html+php文件 + +处理请求 +-------------------- +在引导文件的最后部分,我们使用 Phalcon\\Mvc\\Application ,这个类初始化并执行用户的请求 + +.. code-block:: php + + setDI($di); + echo $application->handle()->getContent(); + +依赖注入 +-------------------- +看上面代码中的第二段,变量$application通过setDI()方法接收了变量$di,该变量的目的是什么呢? + +Phalcon是一个松耦合的框架,所以我们需要一个组件,把它们整合到一起,让它们一起工作,该组件便是 Phalcon\\DI + +注册到容器的方法有很多,在INVO中,大都采用匿名函数的方式进行注册,因为此种方式是lazy load的加载方式,减少了应用程序请求资源控制。 + +例如,在下面的代码片断中的session会话服务,采用的是匿名函数的方式进行注册的,因此当使用session的时候,才会被加载。 + +.. code-block:: php + + set('session', function(){ + $session = new Phalcon\Session\Adapter\Files(); + $session->start(); + return $session; + }); + +在这里,我们可以自由的更改适配器,以使它执行更多的初始化任务,请注意,服务注册的"session"请不要随意修改,这是一个命名约定。 + +译者注:更多的服务组件命名约定可见 :doc:`dependency injection container ` + +一个请求可能使用多个服务组件,一个一个的注册这些组件是一项繁重的任务,出于这个原因,该框架提供了 Phalcon\\DI 的一个实现,就是 Phalcon\\DI\\FactoryDefault + +译者注:其实 Phalcon\\DI\\FactoryDefault 就是 Phalcon\\DI 的一个子类 + +.. code-block:: php + + set('db', function() use ($config) { + return new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => $config->database->host, + "username" => $config->database->username, + "password" => $config->database->password, + "dbname" => $config->database->name + )); + }); + +这时,会返回一个MySQL的连接适配器的实例,如果需要的话,你可以做一些其他额外的操作,例如,你还可以定义一个记录器,分析器或更改为其他适配器。或者设置你想要的其他东西 + +那么,下面的这个表单示例 (app/views/session/index.phtml) 是一个登录入口,已经删除了一些HTML代码,使这个例子更简洁: + +.. code-block:: html+php + + + + + "30")) ?> + + + "30")) ?> + + + + + +SessionController::startAction (app/controllers/SessionController.phtml) 验证用户登录,通过查询数据库的用户的登录名称和密码是否正确 + +.. code-block:: php + + session->set('auth', array( + 'id' => $user->id, + 'name' => $user->name + )); + } + + public function startAction() + { + if ($this->request->isPost()) { + + //Taking the variables sent by POST + $email = $this->request->getPost('email', 'email'); + $password = $this->request->getPost('password'); + + $password = sha1($password); + + //Find for the user in the database + $user = Users::findFirst("email='$email' AND password='$password' AND active='Y'"); + if ($user != false) { + + $this->_registerSession($user); + + $this->flash->success('Welcome '.$user->name); + + //Forward to the invoices controller if the user is valid + return $this->dispatcher->forward(array( + 'controller' => 'invoices', + 'action' => 'index' + )); + } + + $this->flash->error('Wrong email/password'); + } + + //Forward to the login form again + return $this->dispatcher->forward(array( + 'controller' => 'session', + 'action' => 'index' + )); + + } + + } + +需要注意的是控制器中有多个公共属性,如$this->flash,$this->request,$this->session。这些属性在引导文件中使用 Phalcon\\DI 注册的,如果你仔细看过前面的章节,应该能想到。因此可以在控制器中直接使用他们 + +这些服务是共享的,这意味着我们访问的是相同的实例,无论我们在任何地方调用它们。 + +举个例子,在这里我们可以直接调用 "session", 同时把用户的信息存储到变量auth中 + +.. code-block:: php + + session->set('auth', array( + 'id' => $user->id, + 'name' => $user->name + )); + +Securing the Backend +-------------------- +后端是一个私有区域,只有注册的用户才可以访问。因此,它必须进行检查验证,只有注册用户才可以访问这些控制器。如果你没有登录应用程序,你尝试访问的时候,你会看到这样的界面: + +.. figure:: ../_static/img/invo-2.png + :align: center + +每当有人试图访问任何控制器和动作,应用程序就会验证当前用户的角色是否能够访问,否则会显示一个信息,同时跳转到首页面。 + +现在,我们来看看应用程序如何实现这一点。首先要知道的是,有一个组件叫分发器(Dispatcher),你还需要了解一个路由。在此基础上,负载加载相应的控制器和执行相应的动作。 + +通常情况下,框架会自动创建分发器,在这个例子中,我们要专门创建一个动作,显示出用户成功访问和不成功访问的情况。为了实现这一目标,我们更在引导文件(bootstrap)中创建一个函数: + +.. code-block:: php + + set('dispatcher', function() use ($di) { + $dispatcher = new Phalcon\Mvc\Dispatcher(); + return $dispatcher; + }); + +现在,我们的应用程序中就有了控制分发器,现实中,我们需要修改框架中有许多组件的内部流程,这时一个新的组件EventsManager出来了,它可以提供在组件中加入一些其他对像。 + +译者注:如在分发器中加入验证,在数据库连接中加入记录器等 + +事件管理 +^^^^^^^^^^^^^^^^^ +一个事件管理器,可以让我们针听一个特定类型的事件,下面看一下在分发器中加入安全验证的例子: + +.. code-block:: php + + set('dispatcher', function() use ($di) { + + //Obtain the standard eventsManager from the DI + $eventsManager = $di->getShared('eventsManager'); + + //Instantiate the Security plugin + $security = new Security($di); + + //Listen for events produced in the dispatcher using the Security plugin + $eventsManager->attach('dispatch', $security); + + $dispatcher = new Phalcon\Mvc\Dispatcher(); + + //Bind the EventsManager to the Dispatcher + $dispatcher->setEventsManager($eventsManager); + + return $dispatcher; + }); + + +安全插件是一个类文件(app/plugins/Security.php),这个类实现了"beforeExecuteRoute"方法. + +译者注:都可以实现哪些方法,可以查看 :doc:`分发器 ` Dispatch Loop Events 部分 + + +.. code-block:: php + + ` ,但如果这样继承了,他们更容易的访问应用程序的其他服务组件。 + +译者注:目前的 Phalcon\\Mvc\\User\\Plugin 以及 Phalcon\\Mvc\\User\\Component 是一样的,其实两者的侧重点应该是不同的,只是作者还未完善而已。具体请看stackoverflow的贴子 + +http://stackoverflow.com/questions/12879284/whats-different-between-phalcon-mvc-user-component-and-phalcon-mvc-user-plugin + +现在,我们验证登录用户的权限,看他的权限是否在ACL列表中,如果没有(也就是说没有权限的话),分发器将使流程跳转到主页: + +.. code-block:: php + + session->get('auth'); + if (!$auth) { + $role = 'Guests'; + } else { + $role = 'Users'; + } + + //Take the active controller/action from the dispatcher + $controller = $dispatcher->getControllerName(); + $action = $dispatcher->getActionName(); + + //Obtain the ACL list + $acl = $this->_getAcl(); + + //Check if the Role have access to the controller (resource) + $allowed = $acl->isAllowed($role, $controller, $action); + if ($allowed != Phalcon\Acl::ALLOW) { + + //If he doesn't have access forward him to the index controller + $this->flash->error("You don't have access to this module"); + $dispatcher->forward( + array( + 'controller' => 'index', + 'action' => 'index' + ) + ); + + //Returning "false" we tell to the dispatcher to stop the current operation + return false; + } + + } + + } + +Providing an ACL list +^^^^^^^^^^^^^^^^^^^^^ +权限管理部分,我一般不太喜欢使用这种方式的权限验证,不过大多数框架都提供了这种验证,包括ZF。 + +In the previous example we obtain the ACL using the method $this->_getAcl(). This method is also implemented in the Plugin. +Now explain step by step how we built the access control list: + +.. code-block:: php + + setDefaultAction(Phalcon\Acl::DENY); + + //Register two roles, Users is registered users + //and guests are users without a defined identity + $roles = array( + 'users' => new Phalcon\Acl\Role('Users'), + 'guests' => new Phalcon\Acl\Role('Guests') + ); + foreach($roles as $role){ + $acl->addRole($role); + } + +Now we define the respective resources of each area. Controller names are resources and their actions are the accesses in +the resources: + +.. code-block:: php + + array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'), + 'products' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'), + 'producttypes' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'), + 'invoices' => array('index', 'profile') + ); + foreach($privateResources as $resource => $actions){ + $acl->addResource(new Phalcon\Acl\Resource($resource), $actions); + } + + //Public area resources (frontend) + $publicResources = array( + 'index' => array('index'), + 'about' => array('index'), + 'session' => array('index', 'register', 'start', 'end'), + 'contact' => array('index', 'send') + ); + foreach($publicResources as $resource => $actions){ + $acl->addResource(new Phalcon\Acl\Resource($resource), $actions); + } + +The ACL now have knowledge of the existing controllers and their related actions. The role "Users" has access to all the resources +of both the frontend and the backend. The role "Guests" only have access to the public area: + +.. code-block:: php + + $actions) { + $acl->allow($role->getName(), $resource, '*'); + } + } + + //Grant access to private area only to role Users + foreach ($privateResources as $resource => $actions) { + foreach ($actions as $action) { + $acl->allow('Users', $resource, $action); + } + } + +Hooray!, the ACL is now complete. + +用户自定义组件 +--------------- +本应用所有的UI组件和显示风格都是使用的Twitter的CSS Framework。 + +这部分被实现使用成Component (api/library/Elements.php)。 + +译者注:在上面讲Plugins的时候,专门介绍了Component,没注意的可以往上看一下。 + +.. code-block:: php + + set('elements', function(){ + return new Elements(); + }); + +在控制器中以及视图中,插件以及组件可以通过注册的名称很方便的被调用 + +.. code-block:: html+php + + + +
+ getContent() ?> +
+
+

© Company 2012

+
+
+ +重点看这句: + +.. code-block:: html+php + + elements->getMenu() ?> + +增删查改 +--------------------- +大多数菜单选项数据(如公司,产品,产品类型等),我们开发按照普遍的 CRUD_ (Create, Read, Update and Delete)方式,每个CURD包含以下文件: + +.. code-block:: bash + + invo/ + app/ + app/controllers/ + ProductsController.php + app/models/ + Products.php + app/views/ + products/ + edit.phtml + index.phtml + new.phtml + search.phtml + +每个控制器包含以下一些动作(控制器类中的方法): + +译者注:这些动作名称并不是约定的,可以按你的喜好自由修改,比如searchAction,你可以写成soAction都没问题。但请求的时候就不再请求到products/search了,而是需要请求到products/so + +.. code-block:: php + + persistent->searchParams = null; + $this->view->setVar("productTypes", ProductTypes::find()); + } + +所有"product types"将通过变量"productTypes"显示到视图文件中,视图文件(app/views/index.phtml)的代码如下: + +.. code-block:: php + + + + array("id", "name"), + "useDummy" => true + )) ?> + + +变量$productTypes包含的数据通过 :doc:`Phalcon\\Tag::select <../api/Phalcon_Tag>` 填充到视图进行显示。一旦提交检索表单,它会请求到 products/search,并根据用户提交的数据进行数据检索 + +执行一个检索 +^^^^^^^^^^^^^^^^^^^ +"search",即products/search 这个动作具有双重行为,当通过POST访问时,它会根据用户提交的数据进行条件检索。但是,当我们通过GET访问时,将显示所有产品的列表。这些都是通过HTTP方法来进行区分的。详情请查看 :doc:`Request ` component: + +.. code-block:: php + + request->isPost()) { + //create the query conditions + } else { + //paginate using the existing conditions + } + + //... + + } + +使用 :doc:`Phalcon\\Mvc\\Model\\Criteria <../api/Phalcon_Mvc_Model_Criteria>` ,我们可以很方便的把表单提交的数据(值)和数据类型(属性或字段)绑定到一起 + +.. code-block:: php + + di, "Products", $_POST); + +该方法的绑定过程是这样的,首先验证客户端提交的表单数据是否为空""(空字符串),如果不是,将绑定到数据字段上。如果提交的表单数据是字符串类型的(CHAR, VARCHAR, TEXT等),将使用 "like '%%'"这样的形式来进行检索数据。如果不是或不类似于字符串,它会直接使用操作符"="进行检索。 + +此外,如果提交的数据中不包括在数据表字段(也可以说成是model字段)中,这些数据将被忽略。此外,提交的数据会自动使用bound parameter的方式进行绑定。 + +我们把提交的绑定数据存储到session中,此处使用的是 :doc:`Session Bag <../api/Phalcon_Session_Bag>` + +.. code-block:: php + + persistent->searchParams = $query->getParams(); + +Session Bag是一个特殊的属性,它存在于控制器中。这个属性注入的其实是 :doc:`Phalcon\\Session\\Bag <../api/Phalcon_Session_Bag>` 组件。 + +译者注:经测试,使用 $this->persistent->xxx,只能在同一控制器中的不同Action中进行访问,不能在其他控制器中访问到数据。如果需要在不同的控制器访问到变量xxx的数据,可以使用session + +封装绑定好数据后,我们通过这个参数来进行数据检索: + +.. code-block:: php + + flash->notice("The search did not found any products"); + return $this->forward("products/index"); + } + +如果检索不到任何产品,将跳转到 products/index 页面。否则,读取检索到的数据,进行分页显示: + +.. code-block:: php + + $products, //Data to paginate + "limit" => 5, //Rows per page + "page" => $numberPage //Active page + )); + + //Get active page in the paginator + $page = $paginator->getPaginate(); + +最后,把分页的数据绑定到视图上。即把变量$page绑定到视图的page上: + +.. code-block:: php + + view->setVar("page", $page); + +在视图文件(app/views/products/search.phtml) 中,我们这样进行数据显示: + +.. code-block:: html+php + + items as $product){ ?> + + id ?> + getProductTypes()->name ?> + name ?> + price ?> + active ?> + id, 'Edit') ?> + id, 'Delete') ?> + + + +创建以及更新一条数据记录 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +现在,让我们来看看如何使用CURD创建和更新一个记录。通过控制器的"new"和"edit"两个Action,我们可以提交数据输入。他们分别能过"create"和"save"两个Action来保存提交的数据。 + +译者注:说白了就是 newAction就是新建产品页面,点击右上角的Save按钮保存时,会调用createAction。同理.... + +在创建的情况下,我们把用户提交的数据和"products"这个产品实例进行绑定。 + +译者注:即把用户提交的数据通过绑定到model上,以实现保存到数据库的目的。 + +.. code-block:: php + + id = $request->getPost("id", "int"); + $products->product_types_id = $request->getPost("product_types_id", "int"); + $products->name = $request->getPost("name", "striptags"); + $products->price = $request->getPost("price", "double"); + $products->active = $request->getPost("active"); + + //... + + } + +提交的数据被过滤,然后再赋值到对象的属性,保存时,我们就可以知道用户提交的数据有没有符合业务规则。同时,可以在 Products Model中实现验证。 + +.. code-block:: php + + save()) { + + //The store failed, the following messages were produced + foreach ($products->getMessages() as $message) { + $this->flash->error((string) $message); + } + return $this->forward("products/new"); + + } else { + $this->flash->success("Product was created successfully"); + return $this->forward("products/index"); + } + + } + +现在来说产品编辑部分,首先得保证数据库中有可编辑的数据: + +.. code-block:: php + + id); + Tag::displayTo("product_types_id", $product->product_types_id); + Tag::displayTo("name", $product->name); + Tag::displayTo("price", $product->price); + Tag::displayTo("active", $product->active); + + } + +通过 displayTo helper设置从数据库中取得的数据到页面,然后用户可以更改这些数据,然后再通过saveAction保存到数据库。 + +.. code-block:: php + + getPost("id", "int"); + $products = Products::findFirst("id='$id'"); + if ($products == false) { + $this->flash->error("products does not exist ".$id); + return $this->forward("products/index"); + } + + //... assign the values to the object and store it + + } + +动态更改标题 +------------------------------ +当你浏览不同的控制器及动作时,网页标题会不同,如果更改标题呢,可以在每个控制器进行初始化: + +.. code-block:: php + + + + + + + + + + +结束语 +---------- +本教程从各个方面讲解了如何使用Phalcon来创建一个应用程序,希望你也能提供示例程序,同时学习更多的内容。 + +.. _Github: https://github.com/phalcon/invo +.. _CRUD: http://en.wikipedia.org/wiki/Create,_read,_update_and_delete diff --git a/zh/reference/tutorial-rest.rst b/zh/reference/tutorial-rest.rst new file mode 100644 index 000000000000..a22125312bd4 --- /dev/null +++ b/zh/reference/tutorial-rest.rst @@ -0,0 +1,509 @@ +Tutorial 3: Creating a Simple REST API +====================================== +In this tutorial, we will explain how to create a simple application that provides a RESTful_ API using the different HTTP methods: + +* GET to retrieve and search data +* POST to add data +* PUT to update data +* DELETE to delete data + +Defining the API +---------------- + +The API consists of the following methods: + ++--------+----------------------------+----------------------------------------------------------+ +| Method | URL | Action | ++========+============================+==========================================================+ +| GET | /api/robots | Retrieves all robots | ++--------+----------------------------+----------------------------------------------------------+ +| GET | /api/robots/search/Astro | Searches for robots with ‘Astro’ in their name | ++--------+----------------------------+----------------------------------------------------------+ +| GET | /api/robots/2 | Retrieves robots based on primary key | ++--------+----------------------------+----------------------------------------------------------+ +| POST | /api/robots | Adds a new robot | ++--------+----------------------------+----------------------------------------------------------+ +| PUT | /api/robots/2 | Updates robots based on primary key | ++--------+----------------------------+----------------------------------------------------------+ +| DELETE | /api/robots/2 | Deletes robots based on primary key | ++--------+----------------------------+----------------------------------------------------------+ + +Creating the Application +------------------------ +As the application is so simple, we will not implement any full MVC environment to develop it. In this case, we will use a :doc:`micro application ` +to meet our goal. + +The following file structure is more than enough: + +.. code-block:: php + + my-rest-api/ + models/ + Robots.php + index.php + .htaccess + +First, we need an .htaccess file that contains all the rules to rewrite the URIs to the index.php file, that is our application: + +.. code-block:: apacheconf + + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + + +Then, in the index.php file we create the following: + +.. code-block:: php + + handle(); + +Now we will create the routes as we defined above: + +.. code-block:: php + + get('/api/robots', function() { + + }); + + //Searches for robots with $name in their name + $app->get('/api/robots/search/{name}', function($name) { + + }); + + //Retrieves robots based on primary key + $app->get('/api/robots/{id:[0-9]+}', function($id) { + + }); + + //Adds a new robot + $app->post('/api/robots', function() { + + }); + + //Updates robots based on primary key + $app->put('/api/robots/{id:[0-9]+}', function() { + + }); + + //Deletes robots based on primary key + $app->delete('/api/robots/{id:[0-9]+}', function() { + + }); + + $app->handle(); + +Each route is defined with a method with the same name as the HTTP method, as first parameter we pass a route pattern, followed by a handler. In this case +the handler is an anonymous function. The following route: '/api/robots/{id:[0-9]+}', by example, explicitly set that the "id" parameter must have a numeric format. + +When a defined route matches the requested URI then the application will execute the corresponding handler. + +Creating a Model +---------------- +Our API provides information about robots, these data are stored in a database. The following model allows us to access that table in an object oriented way. +We have implemented some business rules using built-in validators and simple validations. Doing this will give us the peace of mind that saved data +meet the requirements of our application: + +.. code-block:: php + + validate(new InclusionIn( + array( + "field" => "type", + "domain" => array("droid", "mechanical", "virtual") + ) + )); + + //Robot name must be unique + $this->validate(new Uniqueness( + array( + "field" => "name", + "message" => "The robot name must be unique" + ) + )); + + //Year cannot be less than zero + if ($this->year < 0) { + $this->appendMessage(new Message("The year cannot be less than zero")); + } + + //Check if any messages have been produced + if ($this->validationHasFailed() == true) { + return false; + } + } + + } + +Now, we must set up a connection to be used by this model: + +.. code-block:: php + + set('db', function(){ + return new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "asimov", + "password" => "zeroth", + "dbname" => "robotics" + )); + }); + + $app = new \Phalcon\Mvc\Micro(); + + //Bind the DI to the application + $app->setDI($di); + +Retrieving Data +--------------- +The first "handler" that we will implement is which by method GET returns all available robots. Let's use PHQL to perform this simple query returning the results as JSON: + +.. code-block:: php + + get('/api/robots', function() use ($app) { + + $phql = "SELECT * FROM Robots ORDER BY name"; + $robots = $app->modelsManager->executeQuery($phql); + + $data = array(); + foreach($robots as $robot){ + $data[] = array( + 'id' => $robot->id, + 'name' => $robot->name, + ); + } + + echo json_encode($data); + + }); + +:doc:`PHQL `, allow us to write queries using a high level, object oriented SQL dialect that internally +translates to the right SQL statements depending on the database system we are using. The clause "use" in the anonymous function allows +us to pass some variables from global to local scope easily. + +The searching by name handler would look like: + +.. code-block:: php + + get('/api/robots/search/{name}', function($name) use ($app) { + + $phql = "SELECT * FROM Robots WHERE name LIKE :name: ORDER BY name"; + $robots = $app->modelsManager->executeQuery($phql, array( + 'name' => '%'.$name.'%' + )); + + $data = array(); + foreach($robots as $robot){ + $data[] = array( + 'id' => $robot->id, + 'name' => $robot->name, + ); + } + + echo json_encode($data); + + }); + +Searching by the field "id" it's quite similar, in this case, we're also notifying if the robot was found or not: + +.. code-block:: php + + get('/api/robots/{id:[0-9]+}', function($id) use ($app) { + + $phql = "SELECT * FROM Robots WHERE id = :id:"; + $robot = $app->modelsManager->executeQuery($phql, array( + 'id' => $id + ))->getFirst(); + + if ($robot==false) { + $response = array('status' => 'NOT-FOUND'); + } else { + $response = array( + 'status' => 'FOUND', + 'data' => array( + 'id' => $robot->id, + 'name' => $robot->name + ) + ); + } + + echo json_encode($response); + }); + +Inserting Data +-------------- +Taking the data as a JSON string inserted in the body of the request, we also use PHQL for insertion: + +.. code-block:: php + + post('/api/robots', function() use ($app) { + + $robot = json_decode($app->request->getRawBody()); + + $phql = "INSERT INTO Robots (name, type, year) VALUES (:name:, :type:, :year:)"; + + $status = $app->modelsManager->executeQuery($phql, array( + 'name' => $robot->name, + 'type' => $robot->type, + 'year' => $robot->year + )); + + //Check if the insertion was successfull + if($status->success()==true){ + + $robot->id = $status->getModel()->id; + + $response = array('status' => 'OK', 'data' => $robot); + + } else { + + //Change the HTTP status + $this->response->setStatusCode(500, "Internal Error")->sendHeaders(); + + //Send errors to the client + $errors = array(); + foreach ($status->getMessages() as $message) { + $errors[] = $message->getMessage(); + } + + $response = array('status' => 'ERROR', 'messages' => $errors); + + } + + echo json_encode($response); + + }); + +Updating Data +------------- +The data update is similar to insertion. The "id" passed as parameter indicates what robot must be updated: + +.. code-block:: php + + put('/api/robots/{id:[0-9]+}', function($id) use($app) { + + $robot = json_decode($app->request->getRawBody()); + + $phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:"; + $status = $app->modelsManager->executeQuery($phql, array( + 'id' => $id, + 'name' => $robot->name, + 'type' => $robot->type, + 'year' => $robot->year + )); + + //Check if the insertion was successfull + if($status->success()==true){ + + $response = array('status' => 'OK'); + + } else { + + //Change the HTTP status + $this->response->setStatusCode(500, "Internal Error")->sendHeaders(); + + $errors = array(); + foreach ($status->getMessages() as $message) { + $errors[] = $message->getMessage(); + } + + $response = array('status' => 'ERROR', 'messages' => $errors); + + } + + echo json_encode($response); + + }); + +Deleting Data +------------- +The data update is similar to insertion. The "id" passed as parameter indicates what robot must be updated: + +.. code-block:: php + + delete('/api/robots/{id:[0-9]+}', function($id) use ($app) { + + $phql = "DELETE FROM Robots WHERE id = :id:"; + $status = $app->modelsManager->executeQuery($phql, array( + 'id' => $id + )); + if($status->success()==true){ + + $response = array('status' => 'OK'); + + } else { + + //Change the HTTP status + $this->response->setStatusCode(500, "Internal Error")->sendHeaders(); + + $errors = array(); + foreach ($status->getMessages() as $message) { + $errors[] = $message->getMessage(); + } + + $response = array('status' => 'ERROR', 'messages' => $errors); + + } + + echo json_encode($response); + + }); + +Testing our Application +----------------------- +Using curl_ we'll test every route in our application verifying its proper operation: + +Obtain all the robots: + +.. code-block:: bash + + curl -i -X GET http://localhost/my-rest-api/api/robots + + HTTP/1.1 200 OK + Date: Wed, 12 Sep 2012 07:05:13 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 117 + Content-Type: text/html; charset=UTF-8 + + [{"id":"1","name":"Robotina"},{"id":"2","name":"Astro Boy"},{"id":"3","name":"Terminator"}] + +Search a robot by its name: + +.. code-block:: bash + + curl -i -X GET http://localhost/my-rest-api/api/robots/search/Astro + + HTTP/1.1 200 OK + Date: Wed, 12 Sep 2012 07:09:23 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 31 + Content-Type: text/html; charset=UTF-8 + + [{"id":"2","name":"Astro Boy"}] + +Obtain a robot by its id: + +.. code-block:: bash + + curl -i -X GET http://localhost/my-rest-api/api/robots/3 + + HTTP/1.1 200 OK + Date: Wed, 12 Sep 2012 07:12:18 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 56 + Content-Type: text/html; charset=UTF-8 + + {"status":"FOUND","data":{"id":"3","name":"Terminator"}} + +Insert a new robot: + +.. code-block:: bash + + curl -i -X POST -d '{"name":"C-3PO","type":"droid","year":1977}' + http://localhost/my-rest-api/api/robots + + HTTP/1.1 200 OK + Date: Wed, 12 Sep 2012 07:15:09 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 75 + Content-Type: text/html; charset=UTF-8 + + {"status":"OK","data":{"name":"C-3PO","type":"droid","year":1977,"id":"4"}} + +Try to insert a new robot with the name of an existing robot: + +.. code-block:: bash + + curl -i -X POST -d '{"name":"C-3PO","type":"droid","year":1977}' + http://localhost/my-rest-api/api/robots + + HTTP/1.1 500 Internal Error + Date: Wed, 12 Sep 2012 07:18:28 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 63 + Content-Type: text/html; charset=UTF-8 + + {"status":"ERROR","messages":["The robot name must be unique"]} + +Or update a robot with an unknown type: + +.. code-block:: bash + + curl -i -X PUT -d '{"name":"ASIMO","type":"humanoid","year":2000}' + http://localhost/my-rest-api/api/robots/4 + + HTTP/1.1 500 Internal Error + Date: Wed, 12 Sep 2012 08:48:01 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 104 + Content-Type: text/html; charset=UTF-8 + + {"status":"ERROR","messages":["Value of field 'type' must be part of + list: droid, mechanical, virtual"]} + +Finally, delete a robot: + +.. code-block:: bash + + curl -i -X DELETE http://localhost/my-rest-api/api/robots/4 + + HTTP/1.1 200 OK + Date: Wed, 12 Sep 2012 08:49:29 GMT + Server: Apache/2.2.22 (Unix) DAV/2 + Content-Length: 15 + Content-Type: text/html; charset=UTF-8 + + {"status":"OK"} + +Conclusion +---------- +As we have seen, develop Restful APIs with Phalcon is easy. Later in the documentation we'll explain in detail how to +use micro applications and the :doc:`PHQL ` language. + +.. _curl : http://en.wikipedia.org/wiki/CURL +.. _RESTful : http://en.wikipedia.org/wiki/Representational_state_transfer \ No newline at end of file diff --git a/zh/reference/tutorial.rst b/zh/reference/tutorial.rst new file mode 100755 index 000000000000..e9dce5c89701 --- /dev/null +++ b/zh/reference/tutorial.rst @@ -0,0 +1,480 @@ +教程 1: 让我们先来学习一个例子 +================================== + +在本节教程中,我们将带您创建一个简单的注册表单的应用程序。 +我们还将解释框架的行为的基本方面。如果你有对自动生成部分代码感兴趣, +您可以查看 :doc:`developer tools `. + +检查您的安装 +-------------------------- +我们假设你已经安装了Phalcon,您可以利用Phpinfo()函数来进行输出查看是否有phalcon出现? + +.. code-block:: php + + + +如果在下面出现了phalcon扩展的字样,那么说明你安装成功了: + +.. code-block:: php + + Array + ( + [0] => Core + [1] => libxml + [2] => filter + [3] => SPL + [4] => standard + [5] => phalcon + [6] => pdo_mysql + ) + +创建一个项目 +------------------ +学习的最好方法是,您按照本教程的指引一步一步的进行. 您可以从此处获得完整的代码 `here `_. + +目录结构 +^^^^^^^^^^^^^^ +Phalcon 是松耦合的,因此并没有对文件的目录作固定,您可以根据您的需要或喜好,自定义文件目录结构 + +本教程的目的和出发点, 我们建议您使用以下类似的文件目录结构: + +.. code-block:: php + + tutorial/ + app/ + controllers/ + models/ + views/ + public/ + css/ + img/ + js/ + +需要注意的是,您不需要包含任何类库到此项目中就可以工作了,因为Phalcon已经当作一个php模块加载进来了. +(译者备注)比如您使用ZF或者其他框架的时候,你要么include进来,要么在include_path中加入框架的路径。但Phalcon却不必这样。 + +完美漂亮的URL +^^^^^^^^^^^^^^ +在本教程中,我们将教你如何做出漂亮的(友好的)网址。友好的URL非常有利于搜索引擎优化,因为它们很容易让用户记住。Phalcon支持最流行的Web服务器的重写。使您的应用程序的URL不完全依赖web server就可以写出很友好的格式。 + +在这个例子中,我们将使用为Apache重写模块。我们使用.htaccess文件的重写规则: + +.. code-block:: apacheconf + + #/.htaccess + + RewriteEngine on + RewriteRule ^$ public/ [L] + RewriteRule (.*) public/$1 [L] + + +All requests to the project will be rewritten to the public/ directory making it the document root. This step ensures that the internal project folders remain hidden from public viewing and thus posing security threats. + +The second set of rules will check if the requested file exists, and if it does it doesn't have to be rewritten by the web server module: + +.. code-block:: apacheconf + + #/public/.htaccess + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L] + + +Bootstrap +^^^^^^^^^ +第一步,你需要创建一个程序的引导文件,这个文件是非常重要的,因为它作为您的应用程序的基础,让你控制它的各个方面,在这个文件中,你可以实现初始化组件以及应用程序的行为 + +一般我们会以index.php为引导程序的入口程序,public/index.php 内容大致如下: + +.. code-block:: php + + registerDirs(array( + '../app/controllers/', + '../app/models/' + ))->register(); + + //Create a DI + $di = new Phalcon\DI\FactoryDefault(); + + //Setting up the view component + $di->set('view', function(){ + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir('../app/views/'); + return $view; + }); + + //Handle the request + $application = new \Phalcon\Mvc\Application(); + $application->setDI($di); + echo $application->handle()->getContent(); + + } catch(\Phalcon\Exception $e) { + echo "PhalconException: ", $e->getMessage(); + } + +类的自动加载 +^^^^^^^^^^^^^^^^^^ +在第一部分,我们发现注册了首先定义了一个autoloader,它的作用是用来自动加载应用中的控制类及模型类等。我们用它可以灵活的加载一个目录或者多个目录中的类。在下面的例子中,我们将介绍如何使用Phalcon\Loader + +有了它,我们可以使用不同的策略来加载类库。下面的例子是自动注册控制器类目录及模型类目录: + +.. code-block:: php + + registerDirs( + array( + '../app/controllers/', + '../app/models/' + ) + )->register(); + +依赖管理 +^^^^^^^^^^^^^^^^^^^^^ +使用Phalcon,你必须了解它的一个非常重要的概念,那就是他的依赖注入容器。听起来很复杂,但实际使用上它是非常简单和实用的。 + +译者注:学过或者对JAVA有些了解的人都应该十分熟悉依赖注入的概念,在早期这个概念被称作IOC(控制反转),后期才被称作DI。它们分别是inversion of control,Dependency Injection的英文缩写。只是DI更能表达其含意,因此后来基本都叫做DI。对这个概念不太懂的人,可以搜索一个这两个英文单词,相信你会有不少收获。 + +一个服务容器就相当于一个袋子,用于存储我们应用将要用到的一些服务,每当框架需要一个组件,将要求服务容器首先注册这个服务组件。Phalcon是一个高度松耦合的框架,Phalcon\DI 将使这些要用到的服务组件透明的结合在一起。 + +.. code-block:: php + + ` 是Phalcon\DI的一个默认实现,为了使开发更容易,它注册了大量的服务组件集成到Phalcon。因此,我们不需要再一个一个的注册这些组件,以后直接使用也没有问题。 + +在接下来的部分,我们将注册一个“view”视图组件,并指定视图文件所在目录,由于视图不同于类文件,它们不能被autoloader自动加载。 + +服务组件可以通过多种方式进行注册,在我们的教程中,我们将使用lambda的匿名函数方式进行注册 + +.. code-block:: php + + set('view', function(){ + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir('../app/views/'); + return $view; + }); + +在最后一部分,我们看到 :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>`. 它的作用是初始化请求,对请求进行URL路由,分发响应,它收集所有的请求,执行并返回响应。 + +.. code-block:: php + + setDI($di); + echo $application->handle()->getContent(); + +正如你所看到的,程序的引导文件是很短的,并且不需要加载任何额外的文件,我们定义的一个MVC应用代码可以少于30行代码。 + +创建一个控制器 +^^^^^^^^^^^^^^^^^^^^^ +默认情况下,Phalcon的控制器名默认为 "index",这么做的原因是在请求中没有传递控制器及动作时,该控制器被自动调用(译者注:ZF等一些框架都是这么做的)默认的控制器(app/controllers/IndexController.php)大概是这个样子的: + +.. code-block:: php + + Hello!"; + } + + } + +控制器的类名都必须以"Controller"结束,控制器类的方法名必须以"Action"结束,如果你通过浏览器访问应用,看到的是这个样子: + +.. figure:: ../_static/img/tutorial-1.png + :align: center + +恭喜你,你的应用已经成功运行! + +视图数据输出 +^^^^^^^^^^^^^^^^^^^^^^^^ +通过控制器向视图输出数据有时候是必要的,但大多数情况下被证实不太理想。Phalcon是根据控制器和动作在视图目录中找到相应的视图文件的,看例子 (app/views/index/index.phtml): + +.. code-block:: php + + Hello!"; + +控制器 (app/controllers/IndexController.php) 定义了一个空的动作,即(indexAction): + +.. code-block:: php + + ` 被自动创建。 + +设计一个注册表单 +^^^^^^^^^^^^^^^^^^^^^^^^ +现在我们将修改 index.phtml 视图文件,同时添加一个新的控制器文件,并命名为"signup".它的作用是让用户可以注册我们的应用。 + +.. code-block:: php + + Hello!"; + + echo Phalcon\Tag::linkTo("signup", "Sign Up Here!"); + +以上代码会生成一个 html "A" 标签,连接到新的 signup 控制器上: + +.. code-block:: html + +

Hello!

Sign Up Here! + +生成html标签,我们使用 :doc:`\Phalcon\\Tag <../api/Phalcon_Tag>`. 更多的html生成方式请查看 :doc:`found here ` + +.. figure:: ../_static/img/tutorial-2.png + :align: center + +下面是Signup控制器文件内容 (app/controllers/SignupController.php): + +.. code-block:: php + + + +

Sign using this form

+ + + +

+ + +

+ +

+ + +

+ +

+ +

+ + + +通过浏览器访问,显示结果如下: + +.. figure:: ../_static/img/tutorial-3.png + :align: center + +:doc:`Phalcon\\Tag <../api/Phalcon_Tag>` 提供了很多的方法生成表章元素. + +The Phalcon\\Tag::form method receives only one parameter for instance, a relative uri to a controller/action in the application. + +点击 "Send" 按钮时,你会发现Phalcon会抛出一个异常,表明我们在控制器中缺少"register" Action, public/index.php 抛出的异常内容如下: + + PhalconException: Action "register" was not found on controller "signup" + +实现registerAction后,异常消除: + +.. code-block:: php + + registerDirs(array( + '../app/controllers/', + '../app/models/' + ))->register(); + + //Create a DI + $di = new Phalcon\DI\FactoryDefault(); + + //Set the database service + $di->set('db', function(){ + return new \Phalcon\Db\Adapter\Pdo\Mysql(array( + "host" => "localhost", + "username" => "root", + "password" => "secret", + "dbname" => "test_db" + )); + }); + + //Setting up the view component + $di->set('view', function(){ + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir('../app/views/'); + return $view; + }); + + //Handle the request + $application = new \Phalcon\Mvc\Application(); + $application->setDI($di); + echo $application->handle()->getContent(); + + } catch(\Phalcon\Exception $e) { + echo "PhalconException: ", $e->getMessage(); + } + +设置正确的数据库连接参数,我们创建的models才能正常工作。 + +使用models存储数据 +^^^^^^^^^^^^^^^^^^^^^^^^^ +接收由表单传过来的数据,并将他们存储到相应的数据表中 + +.. code-block:: php + + request->getPost("name", "string"); + $email = $this->request->getPost("email", "email"); + + $user = new Users(); + $user->name = $name; + $user->email = $email; + + //Store and check for errors + if ($user->save() == true) { + echo "Thanks for register!"; + } else { + echo "Sorry, the following problems were generated: "; + foreach ($user->getMessages() as $message) { + echo $message->getMessage(), "
"; + } + } + } + + } + +用户提交的任何数据都是不可信的,因此我们需要对用户提交的数据进行过滤,只有通过验证和过滤后的内容,才进行保存。这使得应用程序更安全,因为这样避免了常见的攻击,比如SQL注入等 + +在本节教程中,我们使用过滤器过滤一个字符串类型的表单变量,以确保用户提交的内容不包含恶意字符, :doc:`Phalcon\\Filter <../api/Phalcon_Filter>` 使得过滤任务不再复杂,因为我们可以直接使用request中的getPost调用 + +然后实际化Users类,它对应一个User,类的公共属性会映射到users数据表中的字段,通过调用save()方法把该条记录数据存储到数据表。save()方法返回一个 bool值,它告诉我们存储数据是否成功 + +译者注:save()方法是通过继承得来的,因为所有的Model都必须继承自 :doc:`Phalcon\\Mvc\\Model <../api/Phalcon_Mvc_Model>`。再注释一下,别太扣字眼,你当然也可以不继承自 Model,那么你就用不成model的相关功能了:) + +其他的验证会自动发生,比如数据字段定义的not null,即类属性在保存时必须有值。如果我们不输入任何数据直接进行提交,将显示以下内容: + +.. figure:: ../_static/img/tutorial-4.png + :align: center + +结束语 +---------- +这是一个非常简单的教程,你可以看到,你可以使用Phalcon很容易的创建一个应用程序,希望您继续阅读本手册,这样你就可以发现Phalcon提供的更多的附加功能! + +其他的示例 +------------------- +以下的示例也是使用Phalcon开发的,可以下载进行学习。同时欢迎提供更多的完整的示例程序: + +* `INVO application`_: Invoice generation application. Allows for management of products, companies, product types. etc. +* `PHP Alternative website`_: Multilingual and advanced routing application. + +.. _INVO application: http://blog.phalconphp.com/post/20928554661/invo-a-sample-application +.. _PHP Alternative website: http://blog.phalconphp.com/post/24622423072/sample-application-php-alternative-site + diff --git a/zh/reference/url.rst b/zh/reference/url.rst new file mode 100644 index 000000000000..8bea5b6ce0c4 --- /dev/null +++ b/zh/reference/url.rst @@ -0,0 +1,124 @@ +Generating URLs and Paths +========================= + +:doc:`Phalcon\\Mvc\\Url <../api/Phalcon_Mvc_Url>` is the component responsible of generate urls in a Phalcon application. It's capable of produce independent urls based on routes. + +Setting a base URI +------------------ +Dependending of which directory of your document root your application is installed, it may have a base uri or not. + +For example, If your document root is /var/www/htdocs and your application is installed in /var/www/htdocs/invo then your baseUri will be /invo/. If you are using a VirtualHost or your application is installed on the document root then your baseUri is /. Execute the following code to know the base uri detected by Phalcon: + +.. code-block:: php + + getBaseUri(); + +By default, Phalcon automatically may detect your baseUri, but if you want to increase the performance of your application is recommended to set up it manually: + +.. code-block:: php + + setBaseUri('/invo/'); + +Usually, this component must be registered in the Dependency Injector container, so you can setup it on it: + +.. code-block:: php + + set('url', function(){ + $url = new Phalcon\Mvc\Url(); + $url->setBaseUri('/invo/'); + return $url; + }); + +Generating URIs +--------------- +If you are using the :doc:`Router ` with its default behavior. Your application is able the match routes based on the following pattern: /:controller/:action/:params. Accordingly it is easy to create routes that satisfy that pattern (or any other pattern defined in the router) passing a string to the method "get": + +.. code-block:: php + + get("products/save") ?> + +Note that isn't neccesary to prepend the base uri. If you have named routes you can easily change it creating it dinamically. For Example if you have the following route: + +.. code-block:: php + + add('/blog/{$year}/{month}/{title}', array( + 'controller' => 'posts', + 'action' => 'show' + ))->setName('show-post'); + +A URL can be generated in the following way: + +.. code-block:: php + + get(array( + 'for' => 'show-post', + 'year' => 2012, + 'month' => '01', + 'title' => 'some-blog-post' + )); + +Producing URLs without Mod-Rewrite +---------------------------------- +You can use this component also to create urls without mod-rewrite: + +.. code-block:: php + + setBaseUri('/invo/index.php?_url=/'); + + //This produce: /invo/index.php?_url=/products/save + echo $url->get("products/save"); + +You can also use $_SERVER["REQUEST_URI"]: + +.. code-block:: php + + setBaseUri('/invo/index.php?_url=/'); + + //Pass the URI in $_GET["_url"] + $url->setBaseUri('/invo/index.php/'); + +In this case, it's neccesary to manually handle the required URI in the Router: + +.. code-block:: php + + handle($uri); + +The produced routes would look like: + +.. code-block:: php + + get("products/save"); diff --git a/zh/reference/views.rst b/zh/reference/views.rst new file mode 100755 index 000000000000..35a9ea44d0c2 --- /dev/null +++ b/zh/reference/views.rst @@ -0,0 +1,985 @@ +Using Views +=========== +Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the +presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. + +The :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` is responsible for the managing the view layer of your MVC application. + +A hierarchy of files is supported by the component. This hierarchy allows for common layout points (commonly used views), as well as controller +named folders defining respective view templates. + +Integrating Views with Controllers +---------------------------------- +Phalcon automatically passes the execution to the view component as soon as a particular controller has completed its cycle. The view component +will look in the views folder for a folder named as the same name of the last controller executed and then for a file named as the last action +executed. For instance, if a request is made to the URL *http://127.0.0.1/blog/posts/show/301*, Phalcon will parse the URL as follows: + ++-------------------+-----------+ +| Server Address | 127.0.0.1 | ++-------------------+-----------+ +| Phalcon Directory | blog | ++-------------------+-----------+ +| Controller | posts | ++-------------------+-----------+ +| Action | show | ++-------------------+-----------+ +| Parameter | 301 | ++-------------------+-----------+ + +The dispatcher will look for a "PostsController" and its action "showAction". A simple controller file for this example: + +.. code-block:: php + + view->setVar("postId", $postId); + } + + } + +The setVar allows us to create view variables on demand so that they can be used in the view template. The example above demonstrates +how to pass the $postId parameter to the respective view template. + +:doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` uses PHP itself as the template engine, therefore views should have the .phtml extension. +If the views directory is *app/views* then view component will find automatically for these 3 view files. + ++-------------------+-------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Name | File | Description | ++===================+===============================+==========================================================================================================================================================================================================================+ +| Action View | app/views/posts/show.phtml | This is the view related to the action. It only will be shown when the "show" action was executed. | ++-------------------+-------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Controller Layout | app/views/layouts/posts.phtml | This is the view related to the controller. It only will be shown for every action executed within the controller "posts". All the code implemented in the layout will be reused for all the actions in this controller. | ++-------------------+-------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ +| Main Layout | app/views/index.phtml | This is main action it will be shown for every controller or action executed within the application. | ++-------------------+-------------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ + +You are not required to implement all of the files mentioned above. :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` will simply move to the +next view level in the hierarchy of files. If all three view files are implemented, they will be processed as follows: + +.. code-block:: html+php + + + +

This is show view!

+ +

I have received the parameter

+ +.. code-block:: html+php + + + +

This is the "posts" controller layout!

+ + getContent() ?> + +.. code-block:: html+php + + + + + Example + + + +

This is main layout!

+ + getContent() ?> + + + + +Note the lines where the method *$this->getContent()* was called. This method instructs :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` +on where to inject the contents of the previous view executed in the hierarchy. For the example above, the output will be: + +.. figure:: ../_static/img/views-1.png + :align: center + +The generated HTML by the request will be: + +.. code-block:: html+php + + + + + Example + + + +

This is main layout!

+ + + +

This is the "posts" controller layout!

+ + + +

This is show view!

+ +

I have received the parameter 101

+ + + + +Using Templates +--------------- +Templates are views that can be used to share common view code. They act as controller layouts, so you need to place them in the layouts directory. + +.. code-block:: php + + view->setTemplateAfter('common'); + } + + public function lastAction() + { + $this->flash->notice("These are the latest posts"); + } + } + +.. code-block:: html+php + + + + + + Blog's title + + + getContent() ?> + + + +.. code-block:: html+php + + + + + +
getContent() ?>
+ +.. code-block:: html+php + + + +

Blog Title

+ + getContent() ?> + +.. code-block:: html+php + + + +
+

This is a title

+

This is the post content

+
+ +
+

This is another title

+

This is another post content

+
+ +The final output will be the following: + +.. code-block:: html+php + + + + + + Blog's title + + + + + + + +
+ + + +

Blog Title

+ + + +
+

This is a title

+

This is the post content

+
+ +
+

This is another title

+

This is another post content

+
+ +
+ + + + +Using Partials +-------------- +Partial templates are another way of breaking the rendering process into simpler more manageable chunks that can be reused by different +parts of the application. With a partial, you can move the code for rendering a particular piece of a response to its own file. + +One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that your code can be +more easily understood. For example, you might have a view that looks like this: + +.. code-block:: html+php + + partial("shared/ad_banner") ?> + +

Robots

+ +

Check out our specials for robots:

+ ... + + partial("shared/footer") ?> + + +Transfer values from the controller to views +-------------------------------------------- +:doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` is available in each controller using the view variable ($this->view). You can use that +object to set variables directly to the view from a controller action by using the setVar() method. + +.. code-block:: php + + view->setVar("posts", Posts:find()); + } + + } + +A variable with the name of the first parameter of setView() will be created in the view, ready to be used. The variable can be of any type, +from a simple string, integer etc. variable to a more complex structure such as array, collection etc. + +.. code-block:: html+php + +
+ ", $post->title, ""; + } + + ?> +
+ +Control Rendering Levels +------------------------ +As seen above, :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` supports a view hierarchy. You might need to control the level of rendering +produced by the view component. The method Phalcon\Mvc\\View::setRenderLevel() offers this functionality. + +This method can be invoked from the controller or from a superior view layer to interfere with the rendering process. + +.. code-block:: php + + view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER); + + //... + } + + public function showAction($postId) + { + // Shows only the view related to the action + $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW); + } + + } + +The available render levels are: + ++-----------------------+--------------------------------------------------------------------------+ +| Class Constant | Description | ++=======================+==========================================================================+ +| LEVEL_NO_RENDER | Indicates to avoid generating any kind of presentation. | ++-----------------------+--------------------------------------------------------------------------+ +| LEVEL_ACTION_VIEW | Generates the presentation to the view associated to the action. | ++-----------------------+--------------------------------------------------------------------------+ +| LEVEL_BEFORE_TEMPLATE | Generates presentation templates prior to the controller layout. | ++-----------------------+--------------------------------------------------------------------------+ +| LEVEL_LAYOUT | Generates the presentation to the controller layout. | ++-----------------------+--------------------------------------------------------------------------+ +| LEVEL_AFTER_TEMPLATE | Generates the presentation to the templates after the controller layout. | ++-----------------------+--------------------------------------------------------------------------+ +| LEVEL_MAIN_LAYOUT | Generates the presentation to the main layout. File views/index.phtml | ++-----------------------+--------------------------------------------------------------------------+ + +Using models in the view layer +------------------------------ +Application models are always available at the view layer. The :doc:`Phalcon\\Loader <../api/Phalcon_Loader>` will instantiate them at runtime automatically: + +.. code-block:: html+php + +
+ ", $category->name, ""; + } + + ?> +
+ +Although you may perform model manipulation operations such as insert() or update() in the view layer, it is not recommended since it is not +possible to forward the execution flow to another controller in the case of an error or an exception. + +Picking Views +------------- +As mentioned above, when :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` is managed by :doc:`Phalcon\\Mvc\\Application <../api/Phalcon_Mvc_Application>` +the view rendered is the one related with the last controller and action executed. You could override this by using the Phalcon\\Mvc\\View::pick() method: + +.. code-block:: php + + view->pick("products/search"); + } + + } + +Caching View Fragments +---------------------- +Sometimes when you develop dynamic websites and some areas of them are not updated very often, the output is exactly the same between requests. :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` offers caching a part or the whole rendered output to increase performance. + +:doc:`Phalcon\\\Mvc\\View <../api/Phalcon_Mvc_View>` integrates with :doc:`Phalcon\\Cache ` to provide an easier way to cache output fragments. +You could manually set the cache handler or set a global handler: + +.. code-block:: php + + view->cache(true); + } + + public function showArticleAction() + { + // Cache this view for 1 hour + $this->view->cache(array("lifetime" => 3600)); + } + + public function resumeAction() + { + //Cache this view for 1 day with the key "resume-cache" + $this->view->cache( + array( + "lifetime" => 86400, + "key" => "resume-cache", + ) + ); + } + + } + +When the View component needs to cache something it will request a cache service to the services container. The service name convention for this +service is "viewCache": + +.. code-block:: php + + set('viewCache', function(){ + + //Cache data for one day by default + $frontCache = new Phalcon\Cache\Frontend\Output(array( + "lifetime" => 86400 + )); + + //Memcached connection settings + $cache = new Phalcon\Cache\Backend\Memcached($frontCache, array( + "host" => "localhost", + "port" => "11211" + )); + + return $cache; + }); + +Disabling the view +------------------ +If your controller doesn't produce any output in the view (or not even have one) you may disable the view component avoiding unnecessary processing: + +.. code-block:: php + + view->disable(); + + //The same + $this->view->setRenderLevel(Phalcon\Mvc\View::LEVEL_NO_RENDER); + } + + } + +Template Engines +---------------- +Template Engines helps designers to create views without use a complicated syntax. Phalcon includes a powerful and fast templating engine +called :doc:`Volt `. + +Additionally, :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` allows you to use other template engines instead of plain PHP or Volt. + +Using a different template engine, usually requires complex text parsing using external PHP libraries in order to generate the final output +for the user. This usually increases the number of resources that your application are using. + +If an external template engine is used, :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` provides exactly the same view hierarchy and it's +still possible to access the API inside these templates with a little more effort. + +The component uses adapters, these help Phalcon to speak with those external template engines in a unified, let's see how to do that integration. + +Creating your own Template Engine Adapter +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +There are many template engines, which you might want to integrate or create one of your own. The first step to use an external template engine +it's create an adapter for it. + +A template engine adapter is a class that acts as bridge between :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` and the template engine itself. +Usually it only needs two methods implemented: __construct() and render(). The first one receives the :doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` +instance that creates the engine adapter and the DI container used by the application. + +The method render() accepts an absolute path to the view file and the view parameters set using $this->view->setVar(). You could read or require it +when it's necessary. + +.. code-block:: php + + _view; + + // Access options + $options = $this->_options; + + //Render the view + } + + } + +Changing the Template Engine +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +You can replace or add more a template engine from the controller as follows: + +.. code-block:: php + + view->registerEngines( + array( + ".my-html" => "MyTemplateAdapter" + ) + ); + } + + public function showAction() + { + // Using more than one template engine + $this->view->registerEngines( + array( + ".my-html" => 'MyTemplateAdapter' + ".phtml" => 'Phalcon\Mvc\View\Engine\Php' + ) + ); + } + + } + +You can replace the template engine completely or use more than one template engine at the same time. The method \Phalcon\\Mvc\\View::registerEngines() +accepts an array containing data that define the template engines. The key of each engine is an extension that aids in distinguishing one from another. +Template files related to the particular engine must have those extensions. + +The order that the template engines are defined with \Phalcon\\Mvc\\View::reginsterEngines() defines the relevance of execution. If +:doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` finds two views with the same name but different extensions, it will only render the first one. + +If you want to register a template engine or a set of them for each request in the application. You could register it when the view service is created: + +.. code-block:: php + + set('view', function() { + + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines( + array( + ".my-html" => 'MyTemplateAdapter' + ) + ); + + return $view; + }); + +To better explain how to create an adapter for template engines, let's make the integration with two well known: Mustache and Twig. + +Using Mustache +^^^^^^^^^^^^^^ +`Mustache`_ is a logic-less template engine available for many platforms and languages. A PHP implementation is available in `this Github repository`_. + +You need to manually load the Mustache library before use its engine adapter. Either registering an autoload function or including +the relevant file first can achieve this. + +.. code-block:: php + + _mustache = new Mustache_Engine(); + parent::__construct($view, $di); + } + + public function render($path, $params) + { + if (!isset($params['content'])) { + $params['content'] = $this->_view->getContent(); + } + $this->_view->setContent($this->_mustache->render(file_get_contents($path), $params)); + } + + } + +Now, in the controller it's necessary to replace or add the Mustache adapter to the view component. If all of your actions will use this +template engine, you can register it in the initialize() method of the controller. + +.. code-block:: php + + view->registerEngines( + array(".mhtml" => "My_Mustache_Adapter") + ); + + } + + public function showAction() + { + + $this->view->setVar("showPost", true); + $this->view->setVar("title", "some title"); + $this->view->setVar("body", "a cool content"); + + } + + } + +A related view (views-dir/posts/show.mhtml) could be defined using the Mustache syntax: + +.. code-block:: html+php + + {{#showPost}} +

{{title}}

+

{{body}}

+ {{/showPost}} + +Additionally, as seen above, you must call the method $this->getContent() inside a view to include the contents of a view at a higher +level. In Moustache, this can be done as follows: + +.. code-block:: html+php + +
+ +
+ +
+ {{content}} +
+ +Using Twig +^^^^^^^^^^ +Twig_ is a modern template engine for PHP. + +You need to manually load the Twig library before use its engine adapter. Registering its autoloader could do this: + +.. code-block:: php + + getViewsDir()); + $this->_twig = new Twig_Environment($loader); + parent::__construct($view, $di); + } + + public function render($path, $params) + { + $view = $this->_view; + if (!isset($params['content'])) { + $params['content'] = $view->getContent(); + } + if (!isset($params['view'])) { + $params['view'] = $view; + } + $relativePath = str_replace($view->getViewsDir(), '', $path); + $this->_view->setContent($this->_twig->render($relativePath, $params)); + } + + } + +As seen above, it's necessary to replace the default engine by twig or use it together with other. + +.. code-block:: php + + view->registerEngines( + array(".twig" => "Twig") + ); + + } + + public function showAction() + { + + $this->view->setVar("showPost", true); + $this->view->setVar("title", "some title"); + $this->view->setVar("body", "a cool content"); + + } + + } + +In this case, the related view will be views-dir/posts/show.twig, this is a file that contains Twig code: + +.. code-block:: html+php + + {{% if showPost %}} +

{{ title }}

+

{{ body }}

+ {{% endif %}} + +To include the contents of a view at a higher level, the "content" variable is available: + +.. code-block:: html+php + +
+ {{ content }} +
+ +Using Smarty +^^^^^^^^^^^^ +Smarty_ is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic. + +You need to manually include the Smarty library before use its engine adapter. Including its adapter: + +.. code-block:: php + + _smarty = new Smarty(); + $this->_smarty->template_dir = '.'; + $this->_smarty->compile_dir = SMARTY_DIR . 'templates_c'; + $this->_smarty->config_dir = SMARTY_DIR . 'configs'; + $this->_smarty->cache_dir = SMARTY_DIR . 'cache'; + $this->_smarty->caching = false; + $this->_smarty->debugging = true; + parent::__construct($view, $di); + } + + public function render($path, $params) + { + if (!isset($params['content'])) { + $params['content'] = $this->_view->getContent(); + } + foreach($params as $key => $value){ + $this->_smarty->assign($key, $value); + } + $this->_view->setContent($this->_smarty->fetch($path)); + } + + } + +Injecting services in View +-------------------------- +Every view executed is included inside a :doc:`Phalcon\\DI\\Injectable <../api/Phalcon_DI_Injectable>` instance, providing easy access +to the application's service container. + +The following example shows how to write a jQquery `ajax request`_ using a url with the framework conventions. The service "url" is +injected in the view by just only accessing it: + +.. code-block:: html+php + + + + +Stand-Alone Component +--------------------- +All the components in Phalcon can be used as *glue* components individually because they are loosely coupled to each other. Using +:doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` in a stand-alone mode can be demonstrated below: + +.. code-block:: php + + setViewsDir("../app/views/"); + + // Passing variables to the views, these will be created as local variables + $view->setVar("someProducts", $products); + $view->setVar("someFeatureEnabled", true); + + //Start the output buffering + $view->start(); + + //Render all the view hierarchy related to the view products/list.phtml + $view->render("products", "list"); + + //Finish the output buffering + $view->finish(); + + echo $view->getContent(); + +View Events +----------- +:doc:`Phalcon\\Mvc\\View <../api/Phalcon_Mvc_View>` is able to send events to a :doc:`EventsManager ` if it's present. Events +are triggered using the type "view". Some events when returning boolean false could stop the active operation. The following events are supported: + ++----------------------+------------------------------------------------------------+---------------------+ +| Event Name | Triggered | Can stop operation? | ++======================+============================================================+=====================+ +| beforeRender | Triggered before start the render process | Yes | ++----------------------+------------------------------------------------------------+---------------------+ +| beforeRenderView | Triggered before render an existing view | Yes | ++----------------------+------------------------------------------------------------+---------------------+ +| afterRenderView | Triggered after render an existing view | No | ++----------------------+------------------------------------------------------------+---------------------+ +| afterRender | Triggered after complete the render process | No | ++----------------------+------------------------------------------------------------+---------------------+ + +The following example demonstrates how to attach listeners to this component: + +.. code-block:: php + + set('view', function(){ + + //Create an event manager + $eventsManager = new Phalcon\Events\Manager(); + + //Attach a listener for type "view" + $eventsManager->attach("view", function($event, $view) { + echo $event->getType(), ' - ', $view->getActiveRenderPath(), PHP_EOL; + }); + + $view = new \Phalcon\Mvc\View(); + $view->setViewsDir("../app/views/"); + + //Bind the eventsManager to the view component + $view->setEventsManager($eventManagers); + + return $view; + }); + +The following example shows how to create a plugin that clean/repair the HTML produced by the render process using Tidy_: + +.. code-block:: php + + true, + 'output-xhtml' => true, + 'show-body-only' => true, + 'wrap' => 0, + ); + + $tidy = tidy_parse_string($view->getContent(), $tidyConfig, 'UTF8'); + $tidy->cleanRepair(); + + $view->setContent((string) $tidy); + } + + } + + //Attach the plugin as a listener + $eventsManager->attach("view:afterRender", new TidyPlugin()); + +.. _Mustache: https://github.com/bobthecow/mustache.php +.. _Twig: http://twig.sensiolabs.org +.. _this Github repository: https://github.com/bobthecow/mustache.php +.. _ajax request: http://api.jquery.com/jQuery.ajax/ +.. _Smarty: http://www.smarty.net/ +.. _Tidy: http://www.php.net/manual/en/book.tidy.php \ No newline at end of file diff --git a/zh/reference/volt.rst b/zh/reference/volt.rst new file mode 100644 index 000000000000..53b03d79e295 --- /dev/null +++ b/zh/reference/volt.rst @@ -0,0 +1,589 @@ +Volt: Template Engine +===================== + +Volt is an ultra-fast and designer friendly templating language written in C for PHP. It provides you a set of +helpers to write views in an easy way. Volt is highly integrated with other components of Phalcon, +just as you can use it as a stand-alone component in your applications. + +Volt is inspired on Twig_, originally created by Armin Ronacher, which in turn is inspired in Jinja_. +Therefore many developers will be in familiar ground using the same syntax they have been using +with Twig. Volt’s syntax and features have been enhanced with more elements and of course +with the performance that developers have been accustomed to while working with Phalcon. + +Volt views are compiled to pure PHP code, so basically they save the effort of writing PHP code manually: + +.. code-block:: html+jinja + + {# app/views/products/show.volt #} + + {% block last_products %} + + {% for product in products %} + * Name: {{ product.name|e }} + {% if product.status == "Active" %} + Price: {{ product.price + product.taxes/100 }} + {% endif %} + {% endfor %} + + {% endblock %} + +Activating Volt +--------------- +As other template engines, you may register Volt in the view component, using a new extension or +reusing the standard .phtml: + +.. code-block:: php + + set('view', function() { + + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines(array( + ".volt" => 'Phalcon\Mvc\View\Engine\Volt' + )); + + return $view; + }); + +Use the standard ".phtml" extension: + +.. code-block:: php + + registerEngines(array( + ".phtml" => 'Phalcon\Mvc\View\Engine\Volt' + )); + +Basic Usage +----------- +A view consists on Volt code, PHP and HTML. A set of special delimiters is available to enter in +Volt mode. {% ... %} is used to execute statements such as for-loops or assign values and {{ ... }}, +prints the result of a expression to the template. + +Below is a minimal template that illustrates a few basics: + +.. code-block:: html+jinja + + {# app/views/posts/show.phtml #} + + + + {{ title }} - A example blog + + + + {% if show_navigation %} + + {% endif %} + +

{{ post.title }}

+ +
+ {{ post.content }} +
+ + + + +Using Phalcon\\Mvc\\View::setVar you can pass variables from the controller to the views. +In the previous example, three variables were passed to the view: title, menu and post: + +.. code-block:: php + + view->setVar("title", $post->title); + $this->view->setVar("post", $post); + $this->view->setVar("menu", Menu::find()); + $this->view->setVar("show_navigation", true); + + } + + } + +Variables +--------- +Variables may have attributes, those can be accessed using the syntax: foo.bar. If you are +passing arrays, you can access using the curly braces syntax: foo['bar'] + +.. code-block:: jinja + + {{ post.title }} + {{ post['title'] }} + +Filters +------- +Variables can be formatted or modified using filters. The pipe operator | is used to apply filters to +variables: + +.. code-block:: jinja + + {{ post.title|e }} + {{ post.content|striptags }} + {{ name|capitalize|trim }} + +The following is the list of available built-in filters in Volt: + ++----------------------+------------------------------------------------------------------------------+ +| Filter | Description | ++======================+==============================================================================+ +| e | Applies Phalcon\\Escaper->escapeHtml to the value | ++----------------------+------------------------------------------------------------------------------+ +| escape | Applies Phalcon\\Escaper->escapeHtml to the value | ++----------------------+------------------------------------------------------------------------------+ +| trim | Applies the trim_ PHP function to the value. Removing extra spaces | ++----------------------+------------------------------------------------------------------------------+ +| striptags | Applies the striptags_ PHP function to the value. Removing HTML tags | ++----------------------+------------------------------------------------------------------------------+ +| slashes | Applies the slashes_ PHP function to the value. Escaping values | ++----------------------+------------------------------------------------------------------------------+ +| stripslashes | Applies the stripslashes_ PHP function to the value. Removing escaped quotes | ++----------------------+------------------------------------------------------------------------------+ +| capitalize | Capitalizes a string by applying the ucwords_ PHP function to the value | ++----------------------+------------------------------------------------------------------------------+ +| lowercase | Change the case of a string to lowercase | ++----------------------+------------------------------------------------------------------------------+ +| uppercase | Change the case of a string to uppercase | ++----------------------+------------------------------------------------------------------------------+ +| length | Counts the string length or how many items are in an array or object | ++----------------------+------------------------------------------------------------------------------+ +| nl2br | Changes newlines \\n by line breaks (
). Uses the PHP function nl2br_ | ++----------------------+------------------------------------------------------------------------------+ +| sort | Sorts an array using the PHP function asort_ | ++----------------------+------------------------------------------------------------------------------+ +| json_encode | Converts a value into its JSON_ representation | ++----------------------+------------------------------------------------------------------------------+ + +Comments +-------- +Comments may also be added to a template using the {# ... #} delimiters. All text inside them is just ignored in the final output: + +.. code-block:: jinja + + {# note: this is a comment + {% set price = 100; %} + #} + +List of Control Structures +-------------------------- +Volt provides a set of basic but powerful control structures for use in templates: + +For +^^^ +Loop over each item in a sequence. The following example shows how to traverse a set of "robots" and print his/her name: + +.. code-block:: html+jinja + +

Robots

+
    + {% for robot in robots %} +
  • {{ robot.name|e }}
  • + {% endfor %} +
+ +for-loops can also be nested: + +.. code-block:: html+jinja + +

Robots

+ {% for robot in robots %} + {% for part in robot.parts %} + Robot: {{ robot.name|e }} Part: {{ part.name|e }}
+ {% endfor %} + {% endfor %} + +If +^^ +As PHP, a if statement checks if an expression is evaluated as true or false: + +.. code-block:: html+jinja + +

Cyborg Robots

+
    + {% for robot in robots %} + {% if robot.type = "cyborg" %} +
  • {{ robot.name|e }}
  • + {% endif %} + {% endfor %} +
+ +The else clause is also supported: + +.. code-block:: html+jinja + +

Robots

+
    + {% for robot in robots %} + {% if robot.type = "cyborg" %} +
  • {{ robot.name|e }}
  • + {% else %} +
  • {{ robot.name|e }} (not a cyborg)
  • + {% endif %} + {% endfor %} +
+ +Assignments +----------- +Variables may be changed in a template using the instruction "set": + +.. code-block:: html+jinja + + {% set fruits = ['Apple', 'Banana', 'Orange'] %} + {% set name = robot.name %} + +Expressions +----------- +Volt provides a basic set of expression support, including literals and common operators: + ++----------------------+------------------------------------------------------------------------------+ +| Filter | Description | ++======================+==============================================================================+ +| “this is a string” | Text between double quotes or single quotes are handled as strings | ++----------------------+------------------------------------------------------------------------------+ +| 100.25 | Numbers with a decimal part are handled as doubles/floats | ++----------------------+------------------------------------------------------------------------------+ +| 100 | Numbers without a decimal part are handled as integers | ++----------------------+------------------------------------------------------------------------------+ +| false | Constant "false" is the boolean false value | ++----------------------+------------------------------------------------------------------------------+ +| true | Constant "true" is the boolean true value | ++----------------------+------------------------------------------------------------------------------+ +| null | Constant "null" is the Null value | ++----------------------+------------------------------------------------------------------------------+ + +Arrays +^^^^^^ +Whether you're using PHP 5.3 or 5.4, you can create arrays by enclosing a list of values ​​in square brackets: + +.. code-block:: html+jinja + + {# Simple array #} + {{ ['Apple', 'Banana', 'Orange'] }} + + {# Other simple array #} + {{ ['Apple', 1, 2.5, false, null] }} + + {# Multi-Dimensional array #} + {{ [[1, 2], [3, 4], [5, 6]] }} + + {# Hash-style array #} + {{ ['first': 1, 'second': 4/2, 'third': '3'] }} + +Math +^^^^ +You may make calculations in templates using the following operators: + ++----------------------+------------------------------------------------------------------------------+ +| Operator | Description | ++======================+==============================================================================+ +| \+ | Perform an adding operation. {{ 2+3 }} returns 5 | ++----------------------+------------------------------------------------------------------------------+ +| \- | Perform a substraction operation {{ 2-3 }} returns -1 | ++----------------------+------------------------------------------------------------------------------+ +| \* | Perform a multiplication operation {{ 2*3 }} returns 6 | ++----------------------+------------------------------------------------------------------------------+ +| \/ | Perform a division operation {{ 10/2 }} returns 5 | ++----------------------+------------------------------------------------------------------------------+ +| \% | Calculate the remainder of an integer division {{ 10%3 }} returns 1 | ++----------------------+------------------------------------------------------------------------------+ + +Comparisions +^^^^^^^^^^^^ +The following comparision operators are available: + ++----------------------+------------------------------------------------------------------------------+ +| Operator | Description | ++======================+==============================================================================+ +| == | Check whether both operands are equal | ++----------------------+------------------------------------------------------------------------------+ +| != | Check whether both operands aren't equal | ++----------------------+------------------------------------------------------------------------------+ +| \<\> | Check whether both operands aren't equal | ++----------------------+------------------------------------------------------------------------------+ +| \> | Check whether left operand is greater than right operand | ++----------------------+------------------------------------------------------------------------------+ +| \< | Check whether left operand is less than right operand | ++----------------------+------------------------------------------------------------------------------+ +| <= | Check whether left operand is less or equal than right operand | ++----------------------+------------------------------------------------------------------------------+ +| >= | Check whether left operand is greater or equal than right operand | ++----------------------+------------------------------------------------------------------------------+ +| === | Check whether both operands are identical | ++----------------------+------------------------------------------------------------------------------+ +| !== | Check whether both operands aren't identical | ++----------------------+------------------------------------------------------------------------------+ + +Logic +^^^^^ +Logic operators are useful in the "if" expression evaluation to combine multiple tests: + ++----------------------+------------------------------------------------------------------------------+ +| Operator | Description | ++======================+==============================================================================+ +| or | Return true if the left or right operand is evaluated as true | ++----------------------+------------------------------------------------------------------------------+ +| and | Return true if both left and right operands are evaluated as true | ++----------------------+------------------------------------------------------------------------------+ +| not | Negates an expression | ++----------------------+------------------------------------------------------------------------------+ +| ( expr ) | Parenthesis groups expressions | ++----------------------+------------------------------------------------------------------------------+ + +Other Operators +^^^^^^^^^^^^^^^ +Additional operators seen the following operators are available: + ++----------------------+----------------------------------------------------------------------------------------------+ +| Operator | Description | ++======================+==============================================================================================+ +| \~ | Concatenates both operands {{ "hello " \~ "world" }} | ++----------------------+----------------------------------------------------------------------------------------------+ +| \| | Applies a filter in the right operand to the left {{ "hello"\|uppercase }} | ++----------------------+----------------------------------------------------------------------------------------------+ +| \.\. | Creates a range {{ 'a'..'z' }} {{ 1..10 } | ++----------------------+----------------------------------------------------------------------------------------------+ +| is | Same as == (equals) | ++----------------------+----------------------------------------------------------------------------------------------+ +| is not | Same as != (not equals) | ++----------------------+----------------------------------------------------------------------------------------------+ + +The following example shows how to use operators: + +.. code-block:: html+jinja + + {% set robots = ['Voltron', 'Astro Boy', 'Terminator', 'C3PO'] %} + + {% for index in 0..robots|length %} + {% if isset robots[index] %} + {{ "Name: " ~ robots[index] }} + {% endif %} + {% endfor %} + +Using Tag Helpers +----------------- +Volt is highly integrated with :doc:`Phalcon\\Tag `, so it's easy to use the helpers provided by that component in a Volt template: + +.. code-block:: html+jinja + + {{ javascript_include("js/jquery.js") }} + + {{ form('products/save', 'method': 'post') }} + + + {{ text_field("name", "size": 32) }} + + + {{ select("type", productTypes, 'using': ['id', 'name']) }} + + {{ submit_button('Send') }} + + + +The following PHP is generated: + +.. code-block:: html+php + + + + 'post')); ?> + + + 32)); ?> + + + array('id', 'name'))); ?> + + + + + +To call a Phalcon\Tag helper, you only need to call an uncamelized version of the method: + ++------------------------------------+-----------------------+ +| Method | Volt function | ++====================================+=======================+ +| Phalcon\\Tag::linkTo | link_to | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::textField | text_field | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::passwordField | password_field | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::hiddenField | hidden_field | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::fileField | file_field | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::checkField | check_field | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::radioField | radio_field | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::submitButton | submit_button | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::selectStatic | select_static | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::select | select | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::textArea | text_area | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::form | form | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::endForm | end_form | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::getTitle | get_title | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::stylesheetLink | stylesheet_link | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::javascriptInclude | javascript_include | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::image | image | ++------------------------------------+-----------------------+ +| Phalcon\\Tag::friendlyTitle | friendly_title | ++------------------------------------+-----------------------+ + +View Integration +---------------- +Also, Volt is integrated with :doc:`Phalcon\\Mvc\\View `, you can play with the view hierarchy and include partials as well: + +.. code-block:: html+jinja + + {{ content() }} + + {{ partial("partials/footer.volt") }} + +Template Inheritance +-------------------- +With template inheritance you can create base templates that can be extended by others templates allowing to reuse code. A base template +define *blocks* than can be overriden by a child template. Let's pretend that we have the following base template: + +.. code-block:: html+jinja + + {# templates/base.volt #} + + + + {% block head %} + + {% endblock %} + {% block title %}{% endblock %} - My Webpage + + +
{% block content %}{% endblock %}
+ + + + +From other template we could extend the base template replacing the blocks: + +.. code-block:: jinja + + {% extends "templates/base.volt" %} + + {% block title %}Index{% endblock %} + + {% block head %}{% endblock %} + + {% block content %} +

Index

+

Welcome on my awesome homepage.

+ {% endblock %} + +Not all blocks must be replaced at a child template, only those which are needed. The final output produced will be the following: + +.. code-block:: html + + + + + + Index - My Webpage + + +
+

Index

+

Welcome on my awesome homepage.

+
+ + + + +Setting up the Volt Engine +-------------------------- +Volt can be configured to alter its default behavior, the following example explain how to do that: + +.. code-block:: php + + set('voltService', function($view, $di) { + + $volt = new Phalcon\Mvc\View\Engine\Volt($view, $di); + + $volt->setOptions(array( + "compiledPath" => "../app/compiled-templates/", + "compiledExtension" => ".compiled" + )); + + return $volt; + }); + + //Register Volt as template engine + $di->set('view', function() { + + $view = new \Phalcon\Mvc\View(); + + $view->setViewsDir('../app/views/'); + + $view->registerEngines(array( + ".volt" => 'voltService' + )); + + return $view; + }); + +The following options are available in Volt: + ++-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ +| Option | Description | Default | ++===================+================================================================================================================================+=========+ +| compiledPath | A writable path where the compiled PHP templates will be placed | ./ | ++-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ +| compiledExtension | An additional extension appended to the compiled PHP file | .php | ++-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ +| compiledSeparator | Volt replaces the directory separators / and \\ by this separator in order to create a single file in the compiled directory | %% | ++-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ +| stat | Whether Phalcon must check if exists differences between the template file and its compiled path | true | ++-------------------+--------------------------------------------------------------------------------------------------------------------------------+---------+ + + +.. _Twig: https://github.com/vito/chyrp/wiki/Twig-Reference +.. _Jinja: http://jinja.pocoo.org/ +.. _trim: http://php.net/manual/en/function.trim.php +.. _striptags: http://php.net/manual/en/function.striptags.php +.. _slashes: http://php.net/manual/en/function.slashes.php +.. _stripslashes: http://php.net/manual/en/function.stripslashes.php +.. _ucwords: http://php.net/manual/en/function.ucwords.php +.. _nl2br: http://php.net/manual/en/function.nl2br.php +.. _asort: http://php.net/manual/en/function.asort.php +.. _JSON: http://php.net/manual/en/function.json-encode.php \ No newline at end of file diff --git a/zh/reference/wamp.rst b/zh/reference/wamp.rst new file mode 100755 index 000000000000..078be7a13f30 --- /dev/null +++ b/zh/reference/wamp.rst @@ -0,0 +1,49 @@ +Installation on WAMP +===================== + +WampServer_ is a Windows web development environment. It allows you to create web applications with Apache2, PHP and a MySQL database. Below are detailed instructions on how to install Phalcon on WampServer for Windows. Using the latest WampServer version is highly recommended. + +Download the right version of Phalcon +------------------------------------- +WAMP has both 32 and 64 bit versions. From the download section, you can choose the Phalcon for Windows accordingly to your desired architecture. + +After download the Phalcon library you will have a zip file like the one shown below: + +.. figure:: ../_static/img/xampp-1.png + :align: center + +Extract the library from the archive to get the Phalcon DLL: + +.. figure:: ../_static/img/xampp-2.png + :align: center + +Copy the file php_phalcon.dll to the PHP extensions. If WAMP is installed in the c:\\wamp folder, the extension needs to be in C:\\wamp\\bin\\php\\php5.3.10\\ext + +.. figure:: ../_static/img/wamp-1.png + :align: center + +Edit the php.ini file, it is located at C:\\wamp\\bin\\php\\php5.3.10\\php.ini. It can be edited with Notepad or a similar program. We recommend Notepad++ to avoid issues with line endings. Append at the end of the file: extension=php_phalcon.dll and save it. + +.. figure:: ../_static/img/wamp-2.png + :align: center + +Also edit another php.ini file, which is located at C:\\wamp\\bin\\apache\\Apache2.2.21\\bin\\php.ini. Append at the end of the file: extension=php_phalcon.dll and save it. + +Restart the Apache Web Server. Do a single click on the WampServer icon at system tray. Choose "Restart All Services" from the pop-up menu. Check out that tray icon will become green again. + +.. figure:: ../_static/img/wamp-3.png + :align: center + +Open your browser to navigate to http://localhost. The WAMP welcome page will appear. Look at the section "extensions loaded" to check if phalcon was loaded. + +.. figure:: ../_static/img/wamp-4.png + :align: center + +Congrats!, You are now flying with Phalcon. + +Related Guides +-------------- +* :doc:`General Installation ` +* :doc:`Detailed Installation on XAMPP for Windows ` + +.. _WampServer: http://www.wampserver.com/en/ diff --git a/zh/reference/wintools.rst b/zh/reference/wintools.rst new file mode 100644 index 000000000000..9c30b6e49201 --- /dev/null +++ b/zh/reference/wintools.rst @@ -0,0 +1,74 @@ +Phalcon Developer Tools on Windows +================================== +These steps will guide you through the process of installing Phalcon Developer Tools for Windows. + +Prerequisites +------------- +The Phalcon PHP extension is required to run Phalcon Tools. If you haven't installed it yet, please see the :doc:`Installation ` section for instructions. + +Download +-------- +You can download a cross platform package containing the developer tools from the Download_ section. Also you can clone it from Github_. + +On the Windows platform, you need to configure the system PATH to include Phalcon tools as well as the PHP executable. If you download the Phalcon tools as a zip archive, extract it on any path of your local drive i.e. *c:\\phalcon-tools*. You will need this path in the steps below. Edit the file "phalcon.bat" by right clicking on the file and selecting "Edit": + +.. figure:: ../_static/img/path-0.png + :align: center + +Change the path to the one you installed the Phalcon tools: + +.. figure:: ../_static/img/path-01.png + :align: center + +Save the changes. + +Adding PHP and Tools to your system PATH +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Because the scripts are written in PHP, you need to install it on your machine. Depending on your PHP installation, the executable can be located in various places. Search for the file php.exe and copy the path it is located in. For instance, if using the latest WAMP stack, PHP is located in: *C:\\wamp\bin\\php\\php5.3.10\\php.exe*. + +From the Windows start menu, right mouse click on the "My Computer" icon and select "Properties": + +.. figure:: ../_static/img/path-1.png + :align: center + +Click the "Advanced" tab and then the button "Environment Variables": + +.. figure:: ../_static/img/path-2.png + :align: center + +At the bottom, look for the section "System variables" and edit the variable "Path": + +.. figure:: ../_static/img/path-3.png + :align: center + +Be very careful on this step! You need to append at the end of the long string the path where your php.exe was located and the path where Phalcon tools are installed. Use the ";" character to separate the differents paths in the variable: + +.. figure:: ../_static/img/path-4.png + :align: center + +Accept the changes made by clicking "OK" and close the dialogs opened. From the start menu click on the option "Run". If you can't find this option, press "Windows Key" + "R". + +.. figure:: ../_static/img/path-5.png + :align: center + +Type "cmd" and press enter to open the windows command line utility: + +.. figure:: ../_static/img/path-6.png + :align: center + +Type the commands "php -v" and "phalcon" and you will see something like this: + +.. figure:: ../_static/img/path-7.png + :align: center + +Congratulations you now have Phalcon tools installed! + +Related Guides +^^^^^^^^^^^^^^ + +* :doc:`Using Developer Tools ` +* :doc:`Installation on OS X ` +* :doc:`Installation on Linux ` + +.. _Download: http://phalconphp.com/download +.. _Github: https://github.com/phalcon/phalcon-devtools \ No newline at end of file diff --git a/zh/reference/xampp.rst b/zh/reference/xampp.rst new file mode 100755 index 000000000000..bfaea7bf8ddd --- /dev/null +++ b/zh/reference/xampp.rst @@ -0,0 +1,60 @@ +Installation on XAMPP +===================== + +XAMPP_ is an easy to install Apache distribution containing MySQL, PHP and Perl. Once you download XAMPP, all you have to do is extract it and start using it. Below are detailed instructions on how to install Phalcon on XAMPP for Windows. Using the latest XAMPP version is highly recommended. + +Download the right version of Phalcon +------------------------------------- +XAMPP is always releasing 32 bit versions of Apache and PHP. You will need to download the x86 version of Phalcon for Windows from the download section. + +After downloading the Phalcon library you will have a zip file like the one shown below: + +.. figure:: ../_static/img/xampp-1.png + :align: center + +Extract the library from the archive to get the Phalcon DLL: + +.. figure:: ../_static/img/xampp-2.png + :align: center + +Copy the file php_phalcon.dll to the PHP extensions. If you have installed XAMPP in the c:\\xampp folder, the extension needs to be in c:\\xampp\\php\\ext + +.. figure:: ../_static/img/xampp-3.png + :align: center + +Edit the php.ini file, it is located at C:\\xampp\\php\\php.ini. It can be edited with Notepad or a similar program. We recommend Notepad++ to avoid issues with line endings. Append at the end of the file: extension=php_phalcon.dll and save it. + +.. figure:: ../_static/img/xampp-4.png + :align: center + +Restart the Apache Web Server from the XAMPP Control Center. This will load the new PHP configuration. + +.. figure:: ../_static/img/xampp-5.png + :align: center + +Open your browser to navigate to http://localhost. The XAMPP welcome page will appear. Click on the link phpinfo(). + +.. figure:: ../_static/img/xampp-6.png + :align: center + +phpinfo() will output a significant amount of information on screen about the current state of PHP. Scroll down to check if the phalcon extension has been loaded correctly. + +.. figure:: ../_static/img/xampp-7.png + :align: center + +If you can see the phalcon version in the phpinfo() output, congrats!, You are now flying with Phalcon. + +Screencast +---------- +The following screencast is a step by step guide to install Phalcon on Windows: + +.. raw:: html + +
+ +Related Guides +-------------- +* :doc:`General Installation ` +* :doc:`Detailed Installation on WAMP for Windows ` + +.. _XAMPP: http://www.apachefriends.org/en/xampp-windows.html